Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a key/value from one dictionary into another

I have a dict with main data (roughly) as such: {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]}

and I have another dict like: {'UID': 'A12B4', 'other_thing: 'cats'}

I'm unclear how to "join" the two dicts to then put "other_thing" to the main dict. What I need is: {'UID': 'A12B4', 'name': 'John', 'email': '[email protected], 'other_thing': 'cats'}

I'm pretty new to comprehensions like this, but my gut says there has to be a straight forward way.

like image 510
bryan Avatar asked Feb 12 '14 05:02

bryan


People also ask

How do I copy a key value pair to another dictionary in Python?

Using = operator to Copy a Dictionary in Python And directly copy it to a new object dict2 by the code line dict2=dict1. This operation copies references of each object present in dict1 to the new dictionary, dict2. Hence, updating any element of the dict2 will result in a change in dict1 and vice versa.


2 Answers

you want to use the dict.update method:

d1 = {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)

Outputs:

{'email': '[email protected]', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}

From the Docs:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

like image 135
mhlester Avatar answered Sep 22 '22 00:09

mhlester


If you want to join dictionaries, there's a great built-in function you can call, called update.

Specifically:

test = {'A': 1}
test.update({'B': 2})
test
>>> {'A':1, 'B':2}
like image 32
Slater Victoroff Avatar answered Sep 23 '22 00:09

Slater Victoroff