How do you compare 2 dictionaries to know if they have the same item or key?

1

I need to compare 2 dictionaries and return a dictionary with all the elment of both. Example:

dic1 = {'a': 2, 'e': 5, 'u': 1}
dic2 = {'a': 3, 'e': 2, 'i': 2}

then return one of the two complete with all the elements:

dic1 = {'a': 5, 'e': 7, 'i': 2, 'u': 1}
    
asked by José Ignacio 05.10.2018 в 22:57
source

3 answers

2

I think the simplest way would be:

dic1 = {'a': 2, 'e': 5, 'u': 1}
dic2 = {'a': 3, 'e': 2, 'i': 2}

newdict = { k: dic1.get(k, 0) + dic2.get(k, 0) for k in set(dic1) | set(dic2) }
print(newdict)

{'a': 5, 'i': 2, 'u': 1, 'e': 7}

That is:

  • We combine all the keys by set(dic1) | set(dic2)
  • We go through them and add between both dictionaries. When using get() with a default value, there is no problem if a key does not exist in one of the two dictionaries
answered by 05.10.2018 в 23:58
2

If you want to obtain all the unique keys present in at least one of the dictionaries you can use the union of sets:

>>> set(dic1) | set(dic2)
{'a', 'e', 'u', 'i'}

What you really want is to join both dictionaries and add the values, you can apply the union of sets together with dict.get in a dictionary by compression:

dic1 = {'a': 2, 'e': 5, 'u': 1}
dic2 = {'a': 3, 'e': 2, 'i': 2}


res = {key: dic1.get(key, 0) + dic2.get(key, 0) for key in set(dic1) | set(dic2)}
>>> res
{'u': 1, 'a': 5, 'e': 7, 'i': 2}

The construction of the dictionary by compression is efficient, the problem is that iteration is required twice for each dictionary, in addition to the construction of a set for each and a final result of the union. This makes for extended dictionaries more efficient in terms of memory and at run time from a certain point iterate over each dictionary sequentially:

from collections import defaultdict

res = defaultdict(int)
for dict_ in (dic1, dic2):
    for key, value in dict_.items():
        res[key] += value
>>> res
defaultdict(<class 'int'>, {'a': 5, 'e': 7, 'u': 1, 'i': 2})
>>> dict(res)
{'a': 5, 'e': 7, 'u': 1, 'i': 2}
    
answered by 06.10.2018 в 00:00
1

The partners' solutions are really good. I can think of another one that is less elegant and concise because it does not use compression, but that improves efficiency in terms of execution times:

dic1 = {'a': 2, 'e': 5, 'u': 1}
dic2 = {'a': 3, 'e': 2, 'i': 2}

dic3 = dic1.copy()

for k, v in dic2.items():
    dic3[k] = v if k not in dic3.keys() else v + dic3[k]

What works:

>>> dic3
{'a': 5, 'u': 1, 'e': 7, 'i': 2}
    
answered by 06.10.2018 в 15:52