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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With