I have two nested dicts with same master keys:
JavaScript
x
10
10
1
dict1 = {'person1': {'name': 'John', 'sex': 'Male'},
2
'person2': {'name': 'Marie', 'sex': 'Female'},
3
'person3': {'name': 'Luna', 'sex': 'Female'},
4
'person4': {'name': 'Peter', 'sex': 'Male'}}
5
6
dict2 = {'person1': {'weight': '81.1', 'age': '27'},
7
'person2': {'weight': '56.7', 'age': '22'},
8
'person3': {'weight': '63.4', 'age': '24'},
9
'person4': {'weight': '79.1', 'age': '29'}}
10
So I want to enrich dict 1 by the key value pairs from dict2.
I’m able to do so with a for loop…
JavaScript
1
4
1
for key in dict2:
2
dict2[key]['age'] = dict1[key]['age']
3
dict2[key]['weight'] = dict2[key]['weight']
4
Result:
JavaScript
1
5
1
dict2 = {'person1': {'name': 'John', 'sex': 'Male', 'weight': '81.1', 'age': '27'},
2
'person2': {'name': 'Marie', 'sex': 'Female', 'weight': '56.7', 'age': '22'},
3
'person3': {'name': 'Luna', 'sex': 'Female', 'weight': '63.4', 'age': '24'},
4
'person4': {'name': 'Peter', 'sex': 'Male', 'weight': '79.1', 'age': '29'}}
5
…but is there a more pythonic way to do so – e.g. with dict comprehension?
Advertisement
Answer
Yes:
JavaScript
1
2
1
dict3 = {k: {**v, **dict2[k]} for k, v in dict1.items()}
2
Firstly, use .items()
to iterate over both keys and values at the same time.
Then, for each key k
you want the value to be a new dict that is created by dumping — or destructuring — both v
and dict2[k]
in it.
UPDATE for Python >= 3.9:
Thanks @mwo for mentioning the pipe |
operand:
JavaScript
1
2
1
dict3 = {k: v | dict2[k] for k, v in dict1.items()}
2