Search code examples
pythonordereddictionaryordereddict

How to add N OrderDict() in python


Assuming that I have 2 OrderedDict(), I can get the result of the (+) operation by doing the following action:

dict1 = OrderedDict([(52, 0),
         (53, 0),
         (1, 0),
         (2, 0),
         (3, 0),
         (4, 0),
         (5, 0),
         (6, 0),
         (7, 0),
         (8, 0),
         (9, 0),
         (10, 0),
         (11, 1)])

dict2 = OrderedDict([(52, 0),
         (53, 0),
         (1, 0),
         (2, 5),
         (3, 0),
         (4, 0),
         (5, 0),
         (6, 1),
         (7, 0),
         (8, 0),
         (9, 0),
         (10, 1),
         (11, 1)])

dict3 = OrderedDict((k, dict1[k] + dict2[k]) for k in dict1 if k in dict2)
print(dict3)
OrderedDict([(52, 0),
         (53, 0),
         (1, 0),
         (2, 5),
         (3, 0),
         (4, 0),
         (5, 0),
         (6, 1),
         (7, 0),
         (8, 0),
         (9, 0),
         (10, 1),
         (11, 2)])

My question is: how can I generalize the above action so I can get the (+) operation result for N OrderedDict()?


Solution

  • By testing each key for membership of each other dict you're essentially performing an operation of a set intersection, but you can't actually use set intersections because sets are unordered in Python.

    You can work around this limitation by installing the ordered-set package, so that you can use the OrderedSet.intersection method to obtain common keys among the dicts ordered by keys in the first dict, which you can then iterate over to construct a new OrderedDict with each value being the sum of the values of the current key from all dicts:

    from ordered_set import OrderedSet
    
    dicts = [dict1, dict2]
    common_keys = OrderedSet.intersection(*dicts)
    print(OrderedDict((k, sum(d[k] for d in dicts)) for k in common_keys))
    

    Demo: https://replit.com/@blhsing/FlawlessGrowlingAccounting