Concatenate Two Dictionaries | Python How To?

If you want to concatenate two dictionaries in Python (add a dictionary to another dictionary), there is a simple way to do it. Use the update() method which is much like the extend() function used to concatenate lists.

>>> dict_1 = {1: 'a', 2: 'b', 3: 'c'}
>>> dict_2 = {4: 'd', 5: 'e', 6: 'f'}
>>> dict_1
{1: 'a', 2: 'b', 3: 'c'}
>>> dict_2
{4: 'd', 5: 'e', 6: 'f'}
>>> dict_1.update(dict_2)
>>> dict_2
{4: 'd', 5: 'e', 6: 'f'}
>>> dict_1
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}
>>>

What is your other tricks for concatenating Python dictionaries?

Comments

HenrĂ© said…
What would happen if the two dictionaries have an identical key? Eg.

d1 = {1:'hello'}
d2 = {1:'goodbye'}

?
Unknown said…
Hi,
I'm new to Python. I have a question. Didn't know how to contact you. So, it goes this way.
I have a CSV file that needs to be cleaned up. I wrote code with separate functions for each column to replace some value, say 'a' in column 1 with 'aaa', and ' ' (blank) in column 2 with '0'. Can we define only 1 function to do all these? (any maybe write it to a new csv file)
Thanks

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code