I have two list
A = [
{'name':'Tom', 'country':'American', 'birthday': '2001'},
{'name':'Tim', 'country':'India'},
{'name':'Peter', 'country':'China'},
]
B = [
{'name':'Tom', 'country':'China', 'birthday': '...', 'dream': '...'},
]
We think the list A
was a new list and the list B
was the old list.I have some problem about how to write a code to upgrade the old list.
The result will be:
[{'name': 'Tom', 'country': 'China', 'birthday': '2001', 'dream': '...'},
{'name': 'Tim', 'country': 'India'},
{'name': 'Peter', 'country': 'China'}]
I don’t have any idea about this.
I don’t have any idea about this.
>Solution :
Assuming you want to update all keys, using "name" as merging key.
You can build a dictionary of B
using the name as key, then loop over A
to update
each dictionary:
B_dict = {d['name']: d for d in B if 'name' in d}
for d in A:
if 'name' in d:
d.update(B_dict.get(d['name'], {}))
Output:
[{'name': 'Tom', 'country': 'China', 'birthday': '...', 'dream': '...'},
{'name': 'Tim', 'country': 'India'},
{'name': 'Peter', 'country': 'China'}]
Just in case ...
have a special meaning and you only want to add them if there is not already a non ...
value, you can tweak the above approach to only pass the key:...
for which there is not already an existing valid value:
B_dict = {d['name']: d for d in B if 'name' in d}
for d in A:
if 'name' in d:
d.update({k: v for k,v in B_dict.get(d['name'], {}).items()
if v != '...' or k not in d})
Output:
[{'name': 'Tom', 'country': 'China', 'birthday': '2001', 'dream': '...'},
{'name': 'Tim', 'country': 'India'},
{'name': 'Peter', 'country': 'China'}]