Home > other >  addition of two dictionaries with negative numbers
addition of two dictionaries with negative numbers

Time:07-29

Could someone advise on why addition of two dictionaries does not work? It appears that when the sum is negative, the results is dropped out of the dictionary. If one of the values is negative but the sum is still positive, the result shows in the addition.

dict_a = {'A':1, 'B':-2, 'C':3}
dict_b = {'B':-4, 'C':-5, 'D':6}

dict( collections.Counter(dict_a)   collections.Counter(dict_b) )

The result of the summation is:

{'A': 1, 'D': 6}

CodePudding user response:

From the documentation of collections.Counter:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Equality and inclusion compare corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

See the highlighted portion, which explains why the negative counts are removed.

CodePudding user response:

Based on your title, I understood, you're tying to sum the values of two dictionaries. here is an approach without counter method

dict1 = {'A':1, 'B':-2, 'C':3}
dict2 = {'B':-4, 'C':-5, 'D':6}
 
for key in dict2:
    if key in dict1:
        dict2[key] = dict2[key]   dict1[key]
         
print(dict2)

Output:

{'B': -6, 'C': -2, 'D': 6}

Based on the suggestion by @Barmer:

from collections import defaultdict
 
dict1 = {'A':1, 'B':-2, 'C':3}
dict2 = {'B':-4, 'C':-5, 'D':6}

ret = defaultdict(int)
tests = [dict1, dict2]
for d in tests:
    for k, v in d.items():
        ret[k]  = v

print(dict(ret))

Output:

{'A': 1, 'B': -6, 'C': -2, 'D': 6}

CodePudding user response:

Try that:

a = {'A':1, 'B':-2, 'C':3}
b = {'B':-4, 'C':-5, 'D':6}
{k:a[k] b[k] for k in (set(a) & set(b))}
# {'C': -2, 'B': -6}
{k:a[k] b[k] for k in (set(a) & set(b))} | {k: a[k] for k in (set(a)-set(b))} | {k: b[k] for k in (set(b)-set(a))}
# {'C': -2, 'B': -6, 'A': 1, 'D': 6
  • Related