2

I have one list of dictionary like this:

data = [{"name":"Kane", "age": 29},
        {"name":"will", "age": "32"}]


dtat_2 = [ {"Team":"SRH", "Country" :"NZ"},
           {"Team":"RCB", "Country" :"WI"}]

Expected output:

data3 = [{"name":"Kane", "age": 29, "Team":"SRH", "Country" :"NZ"},
         {"name":"will", "age": "32", "Team":"RCB", "Country" :"WI"}]

How can I do this?

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Does this answer your question? [Merge two list contained dictionary based on its index in python](https://stackoverflow.com/questions/42311288/merge-two-list-contained-dictionary-based-on-its-index-in-python) – Ankur Sinha Dec 19 '19 at 07:30
  • Do you mean sql-like ```join```? I.e. can it happen, that e.g. data will have more elements, with at least 2 refering to one and the same element from ```dtat_2```? – Grzegorz Skibinski Dec 19 '19 at 07:58

1 Answers1

8

On python >= 3.5 you can zip the lists and unpack them like this:

[{**d1, **d2} for d1, d2 in zip(data, dtat_2)]
# [{'Country': 'NZ', 'Team': 'SRH', 'age': 29, 'name': 'Kane'},
#  {'Country': 'WI', 'Team': 'RCB', 'age': '32', 'name': 'will'}]

Another one that should work for any version is in-place update, this updates one of the dictionaries (just fyi).

for d1, d2 in zip(data, dtat_2):
    d1.update(d2)

data
# [{'Country': 'NZ', 'Team': 'SRH', 'age': 29, 'name': 'Kane'},
#  {'Country': 'WI', 'Team': 'RCB', 'age': '32', 'name': 'will'}]
cs95
  • 379,657
  • 97
  • 704
  • 746