Copy key / value from one dictionary to another

I have a dict with basic data (approximately): {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}

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

I don’t understand how to “join” two speakers, then put “other_thing” in the main dict. I need:{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com, 'other_thing': 'cats'}

I am new to such insights, but my opinion says that there should be a direct path.

+4
source share
2 answers

you want to use the method dict.update:

d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)

Outputs:

{'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}

From the docs :

Update the dictionary using key / value pairs from another, overwriting existing keys. Refund None.

+14
source

, , , update.

:

test = {'A': 1}
test.update({'B': 2})
test
>>> {'A':1, 'B':2}
+2

Source: https://habr.com/ru/post/1526474/


All Articles