1

I've two dictionaries, output of factorint from sympy.ntheory. I need to merge them so that the common keys gets their values summed up, i.e. MergedDict[key] = Dict1[key] + Dict2[key], while unique keys remain same.

Also I need to get a merged dictionary with the common keys being differenced, i.e. MergedDict[key] = Dict1[key] - Dict2[key]. Here Dict2 keys will be always a subset of Dict1 keys, so no problem of negative numbers.

I've tried to follow this question. But I'm unable to make it work. So far my approach has been as follows:

from sympy.ntheory import factorint
from collections import defaultdict

d=factorint(12)
dd = defaultdict(lambda: defaultdict(int))
for key, values_dict in d.items():
            for date, integer in values_dict.items():
                dd[key] += integer

for n in range(2,6):
    u = factorint(n)

    for key, values_dict in u.items():
        for date, integer in values_dict.items():
            dd[key] += integer

It gives the error AttributeError: 'int' object has no attribute 'items'. The code above in only for the summing up part. Yet to do anything on the differencing part, assuming that summing up can be changed to work for differencing in case of common keys.

Community
  • 1
  • 1
Frash
  • 724
  • 1
  • 10
  • 19
  • d is a `dict` object as output by `factorint`, not sure what you mean by "why are you expecting a dict?". If the approach is wrong please tell. – Frash Oct 11 '15 at 12:33
  • yes factorint is a dict but the values stored in the dict are not dictionaries. `values_dict` in your code is an int not a dict – Padraic Cunningham Oct 11 '15 at 12:37

2 Answers2

2

Not sure what you goal is but factorint gives you key/value pairs of ints so you should be summing the values, you are trying to call items on each val from the dict which is an integer and obviously not going to work:

    from sympy.ntheory import factorint
    from collections import defaultdict

    d=factorint(12)
    dd = defaultdict(int)
    for key, val in d.items():
       dd[key] += val

    for n in range(2, 6):
        u = factorint(n)
        for key, val in u.items():
                dd[key] += val

    print(dd)

Output:

 defaultdict(<type 'int'>, {2: 5, 3: 2, 5: 1})

factorint being a dict cannot have duplicate keys so the first loop cann be done using update:

d = factorint(12)
dd = defaultdict(int)
dd.update(d)

for n in range(2, 6):
    u = factorint(n)
    for key, val in u.items():
            dd[key] += val
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

It seems that collections.Counter can do most of what you want. It might be as simple as (untested, I do not have sympy installed):

from collections import Counter
cnt1 = Counter(Dict1)
cnt2 = Counter(Dict2)
sum_cnt = cnt1 + cnt2
diff_cnt = cnt1 - cnt2
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62