Christ Adam
Christ Adam

Reputation: 31

How to compare two list value and append that value to new list?

list1 = [{'name': 'Tyler', 'age': '12', 'city': 'SF'}, {'name': 'Caitlyn', 'age': '10', 'city': 'SJ'}]
list2 = [{'age': '12', 'hobby': 'soccer', 'song': 'Abba'}, {'age': '10', 'hobby': 'baseball', 'song': 'Punk'}]

Here are the two lists and I want to compare the age in each list that matches and append it to list1. Can you guys help me with this?

The results should be

list1 = [{'name': 'Tyler', 'age': '12', 'city': 'SF', 'age': '12', 'hobby': 'soccer', 'song': 'Abba'}, {'name': 'Caitlyn', 'age': '10', 'city': 'SJ', 'age': '10', 'hobby': 'baseball', 'song': 'Punk'}]

Thanks!

Upvotes: 0

Views: 121

Answers (3)

Alexander McFarlane
Alexander McFarlane

Reputation: 11293

Python 2 An operation as follows

for d in list1:
    for e in list2:
        if d['age'] == e['age']:
            d.update(e)

Python 3 You can write in one line as

[{**d, **e} if d['age'] == e['age'] else d for d in list1 for e in list2]

Upvotes: 0

robinsax
robinsax

Reputation: 1220

If I understand correctly, you want to join each dictionary in list2 into the dictionary in list1 with the same value in the age key.

Try something like this

def join_by_age(list1, list2):
    for item1 in list1:
        for item2 in list2:
            if item1['age'] == item2['age']:
                item1.update(item2)
                break
    return list1

# Join the two lists.
print(join_by_age(list1, list2))

Keep in mind that the dictionaries in list1 will be modified and that if multiple dictionaries in list2 have the same age, only the first will ever be used.

Upvotes: 1

jpp
jpp

Reputation: 164623

You can manipulate lists of dictionaries, but for practical purposes this isn't the most efficient or adaptable structure for what you're looking to do.

If you are happy to use a 3rd party library, you can use Pandas and pd.DataFrame.merge:

import pandas as pd

res = pd.DataFrame(list1).merge(pd.DataFrame(list2))

You can then output either a dataframe or a list of dictionaries:

print(res)

  age city     name     hobby  song
0  12   SF    Tyler    soccer  Abba
1  10   SJ  Caitlyn  baseball  Punk

print(res.to_dict('records'))

[{'age': '12', 'city': 'SF', 'name': 'Tyler', 'hobby': 'soccer', 'song': 'Abba'}, 
 {'age': '10', 'city': 'SJ', 'name': 'Caitlyn', 'hobby': 'baseball', 'song': 'Punk'}]

Upvotes: 0

Related Questions