Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update list contents

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading