25
votes

I am trying to merge the following python dictionaries as follow:

dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10}
dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}

output = {'paul':[100,'a'],
          'john':[80, 'b'],
          'ted':[34,'c'],
          'peter':[None, 'd'],
          'herve':[10, None]}

Is there an efficient way to do this?

4
I wish to keep all keys from both dictionariesJoey
Please don't add comments to your own question. It's your question. You can update the question so that it's correct. Comments are for others to comment on your question.S.Lott
@rcreswick's answer to <a href="stackoverflow.com/questions/38987/… question</a> should suit your needs.Seth
A little formatting would go a long way here. Try editing your question: select the code and click the "101 010" button in the edit window. Also, separate dict1 & dict2 into two separate lines.Pete
See also: similar questiondreftymac

4 Answers

22
votes
output = {k: [dict1[k], dict2.get(k)] for k in dict1}
output.update({k: [None, dict2[k]] for k in dict2 if k not in dict1})
16
votes

This will work:

{k: [dict1.get(k), dict2.get(k)] for k in set(dict1.keys() + dict2.keys())}

Output:

{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
9
votes

In Python2.7 or Python3.1 you can easily generalise to work with any number of dictionaries using a combination of list, set and dict comprehensions!

>>> dict1 = {'paul':100, 'john':80, 'ted':34, 'herve':10}
>>> dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}
>>> dicts = dict1,dict2
>>> {k:[d.get(k) for d in dicts] for k in {k for d in dicts for k in d}}
{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}

Python2.6 doesn't have set comprehensions or dict comprehensions

>>> dict1 = {'paul':100, 'john':80, 'ted':34, 'herve':10}
>>> dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}
>>> dicts = dict1,dict2
>>> dict((k,[d.get(k) for d in dicts]) for k in set(k for d in dicts for k in d))
{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}
2
votes

In Python3.1,

output = {k:[dict1.get(k),dict2.get(k)] for k in dict1.keys() | dict2.keys()}
In Python2.6,
output = dict((k,[dict1.get(k),dict2.get(k)]) for k in set(dict1.keys() + dict2.keys()))