Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can 2 Python dictionaries become 1? [duplicate]

Tags:

Possible Duplicate:
Python “extend” for a dictionary

I know that Python list can be appended or extended. Is there an easy way to combine two Python dictionaries with unique keys, for instance:

basket_one = {'fruit': 'watermelon', 'veggie': 'pumpkin'} basket_two = {'dairy': 'cheese', 'meat': 'turkey'} 

I then want one big basket of food:

basket = {     'fruit': 'watermelon',      'veggie': 'pumpkin',      'dairy': 'cheese',      'meat': 'turkey' } 

How can I perform the above in Python?

like image 268
Thierry Lam Avatar asked Oct 11 '09 20:10

Thierry Lam


People also ask

Can we merge two dictionaries?

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 dictionaries in Python have duplicates?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Do dictionaries allow duplicates?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

The "oneliner way", altering neither of the input dicts, is

basket = dict(basket_one, **basket_two) 

In case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or hear towards learning about dict and the ** form;-). So, for example, uses like:

x = mungesomedict(dict(adict, **anotherdict)) 

are reasonably frequent occurrences in my code.

Note: In Python 3, this will only work if every key in anotherdict is a string. See these alternatives.

like image 84
Alex Martelli Avatar answered Oct 04 '22 20:10

Alex Martelli