Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Iterating through two lists that contain dictionaries, appending matches to a third list

Writer Matthew Barrera

I have two lists that contain dictionaries:

list105 = [
{'Country': 'Zimbabwe', 'GDP/Pop 2005': 281.0751453319367}
{'Country': 'Zambia', 'GDP/Pop 2005': 654.055392253311}
{'Country': 'Congo (Dem. Rep.)', 'GDP/Pop 2005': 115.37122637190915}
]
list202 = [
{'Country': 'Vietnam', 'GDP/Pop 2002': 633.4709249146734}
{'Country': 'Zambia', 'GDP/Pop 2002': 1198.4556066429468}
{'Country': 'Vanuatu', 'GDP/Pop 2002': 1788.4344216880352}
]

Is it possible to iterate through both lists of dictionaries, match the 'Country' key, and append all unique keys from either dictionary to a new dictionary created in the third list?E.g. following from above, the third list would contain:

list2and3 = [
{'Country': 'Zambia', 'GDP/Pop 2005': 654.055392253311, 'GDP/Pop 2002': 1198.4556066429468}
]

I've started off with something like:

list2and3 = []
for line in list105: for row in list202: if line['Country'] == row['Country']: #do something and append to list2and3
3

3 Answers

Convert the first list to a dict:

d = {x['Country']:x for x in list105}

Then iterate the second list and add data to the dict:

for item in list202: key = item['Country'] if key in d: d[key].update(item) else: d[key] = item

Finally, apply .values() to convert the dict back to a list:

newlist = d.values()

Note: this data structure is sub-optimal, consider rethinking it.

from copy import deepcopy
list2and3 = []
for line in list105: for row in list202: if line['Country'] == row['Country']: dic = deepcopy(line) # creates a deepcopy of row, so that the dic.update(row) # update operation doesn't affects the original object list2and3.append(dic)
print list2and3

output:

[{'Country': 'Zambia', 'GDP/Pop 2005': 654.055392253311, 'GDP/Pop 2002': 1198.4556066429468}]
1

You may want a better solution without loop.

[x for x in list105 for y in list202 if x['Country'] == y['Country'] and x != y and not x.update(y)]

1 list comprehesion can lead you to the answer but it may be not human-friendly. Just choose what you like.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy