How to add two dictionaries in python with same keys

To supplement the two-list solutions, here is a solution for processing a single list.

A sample list (NetworkX-related; manually formatted here for readability):

ec_num_list = [((src, tgt), ec_num['ec_num']) for src, tgt, ec_num in G.edges(data=True)]

print('\nec_num_list:\n{}'.format(ec_num_list))
ec_num_list:
[((82, 433), '1.1.1.1'),
  ((82, 433), '1.1.1.2'),
  ((22, 182), '1.1.1.27'),
  ((22, 3785), '1.2.4.1'),
  ((22, 36), '6.4.1.1'),
  ((145, 36), '1.1.1.37'),
  ((36, 154), '2.3.3.1'),
  ((36, 154), '2.3.3.8'),
  ((36, 72), '4.1.1.32'),
  ...] 

Note the duplicate values for the same edges (defined by the tuples). To collate those "values" to their corresponding "keys":

from collections import defaultdict
ec_num_collection = defaultdict(list)
for k, v in ec_num_list:
    ec_num_collection[k].append(v)

print('\nec_num_collection:\n{}'.format(ec_num_collection.items()))
ec_num_collection:
[((82, 433), ['1.1.1.1', '1.1.1.2']),   ## << grouped "values"
((22, 182), ['1.1.1.27']),
((22, 3785), ['1.2.4.1']),
((22, 36), ['6.4.1.1']),
((145, 36), ['1.1.1.37']),
((36, 154), ['2.3.3.1', '2.3.3.8']),    ## << grouped "values"
((36, 72), ['4.1.1.32']),
...] 

If needed, convert that list to dict:

ec_num_collection_dict = {k:v for k, v in zip(ec_num_collection, ec_num_collection)}

print('\nec_num_collection_dict:\n{}'.format(dict(ec_num_collection)))
  ec_num_collection_dict:
  {(82, 433): ['1.1.1.1', '1.1.1.2'],
  (22, 182): ['1.1.1.27'],
  (22, 3785): ['1.2.4.1'],
  (22, 36): ['6.4.1.1'],
  (145, 36): ['1.1.1.37'],
  (36, 154): ['2.3.3.1', '2.3.3.8'],
  (36, 72): ['4.1.1.32'],
  ...}

References

  • [this thread] How to merge multiple dicts with same key?
  • [Python docs] https://docs.python.org/3.7/library/collections.html#collections.defaultdict

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary.

    Let’s see how to combine the values of two dictionaries having same key.

    Method #1: Using Counter
    Counter is a special subclass of dictionary which performs acts same as dictionary in most cases.

    from collections import Counter

    ini_dictionary1 = Counter({'nikhil': 1, 'akash' : 5,

                         'manjeet' : 10, 'akshat' : 15})

    ini_dictionary2 = Counter({'akash' : 7, 'akshat' : 5,

                                              'm' : 15})

    print ("initial 1st dictionary", str(ini_dictionary1))

    print ("initial 2nd dictionary", str(ini_dictionary2))

    final_dictionary = ini_dictionary1 + ini_dictionary2

    print ("final dictionary", str(final_dictionary))

    Output:

    initial 1st dictionary Counter({‘akshat’: 15, ‘manjeet’: 10, ‘akash’: 5, ‘nikhil’: 1})
    initial 2nd dictionary Counter({‘m’: 15, ‘akash’: 7, ‘akshat’: 5})
    final dictionary Counter({‘akshat’: 20, ‘m’: 15, ‘akash’: 12, ‘manjeet’: 10, ‘nikhil’: 1})

     
    Method #2: Using dict() and items
    This method is for Python version 2.

    ini_dictionary1 = {'nikhil': 1, 'akash' : 5,

                  'manjeet' : 10, 'akshat' : 15}

    ini_dictionary2 = {'akash' : 7, 'akshat' : 5,

                                        'm' : 15}

    print ("initial 1st dictionary", str(ini_dictionary1))

    print ("initial 2nd dictionary", str(ini_dictionary2))

    final_dictionary = dict(ini_dictionary1.items() + ini_dictionary2.items() +

                        [(k, ini_dictionary1[k] + ini_dictionary2[k])

                        for k in set(ini_dictionary2)

                        & set(ini_dictionary1)])

    print ("final dictionary", str(final_dictionary))

    Output:

    (‘initial 1st dictionary’, “{‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15, ‘akash’: 5}”)
    (‘initial 2nd dictionary’, “{‘m’: 15, ‘akshat’: 5, ‘akash’: 7}”)
    (‘final dictionary’, “{‘nikhil’: 1, ‘m’: 15, ‘manjeet’: 10, ‘akshat’: 20, ‘akash’: 12}”)

     
    Method #3: Using dict comprehension and set

    ini_dictionary1 = {'nikhil': 1, 'akash' : 5

                  'manjeet' : 10, 'akshat' : 15}

    ini_dictionary2 = {'akash' : 7, 'akshat' : 5

                                        'm' : 15}

    print ("initial 1st dictionary", str(ini_dictionary1))

    print ("initial 2nd dictionary", str(ini_dictionary2))

    final_dictionary =  {x: ini_dictionary1.get(x, 0) + ini_dictionary2.get(x, 0)

                        for x in set(ini_dictionary1).union(ini_dictionary2)}

    print ("final dictionary", str(final_dictionary))

    Output:

    initial 1st dictionary {‘nikhil’: 1, ‘akshat’: 15, ‘akash’: 5, ‘manjeet’: 10}
    initial 2nd dictionary {‘akshat’: 5, ‘akash’: 7, ‘m’: 15}
    final dictionary {‘nikhil’: 1, ‘akshat’: 20, ‘akash’: 12, ‘m’: 15, ‘manjeet’: 10}


    Can we add two dictionaries in Python?

    Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

    Can two dictionary keys have the same value?

    No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

    How do I add multiple dictionaries to a list in Python?

    | operator, |= operator (Python 3.9 or later) Since Python 3.9, it is possible to merge two dictionaries with the | operator. If they have the same key, it is overwritten by the value on the right. You can combine multiple dictionaries. Like += for + , |= for | is also provided.

    How do you sum and merge dictionaries in Python?

    To merge two dictionaries and sum the values:.
    Use a dict comprehension to iterate over one of the dictionaries..
    On each iteration, use the dict. get() method to sum the values..
    Specify a default value of 0 in case a key in one dict is not present in the other..