I have a list of dictionaries containing lists of dictionaries containing a dictionary:
super_data: [{'data': [{'attributes': {'stuff': 'test'
'stuff2': 'tester'}
}]}
{'data': [{'attributes': {'stuff': 'test2'
'stuff2': 'tester2'}
}]}
I have other lists of dictionaries which might look like:
super_meta_data: [{'meta_data': [{'attributes': {'thing': 'testy'
'thing2': 'testy2'}
}]}
{'meta_data': [{'attributes': {'thing': 'testy3'
'thing': 'testy4'}
}]}
I want to merge the nested list of dicts like so:
super_data: [{'data': [{'attributes': {'stuff': 'test'
'stuff2': 'tester'}
}]
'meta_data': [{'attributes': {'thing': 'testy'
'thing2': 'testy2'}
}]
}
{'data': [{'attributes': {'stuff': 'test'
'stuff2': 'tester'}
}]
'meta_data': [{'attributes': {'thing': 'testy3'
'thing2': 'testy4'}
}]
}
How would I go about doing that? I’m trying:
for i in super_data:
super_data.append([i][super_meta_data]
But it’s throwing:
TypeError: list indices must be integers or slices, not dict
Appreciate any insight!
Advertisement
Answer
You might try the following, using zip:
for data, meta_data in zip(super_data, super_meta_data):
data.update(meta_data)
Or, with the same result, using a list comprehension:
super_data = [{**d, **md} for d, md in zip(super_data, super_meta_data)]
>>> super_data
[{'data': [{'attributes': {'stuff': 'test', 'stuff2': 'tester'}}],
'meta_data': [{'attributes': {'thing': 'testy', 'thing2': 'testy2'}}]},
{'data': [{'attributes': {'stuff': 'test2', 'stuff2': 'tester2'}}],
'meta_data': [{'attributes': {'thing': 'testy3', 'thing2': 'testy4'}}]}]
If you want to make your index-based approach work:
for i in range(len(super_data)):
super_data[i].update(super_meta_data[i])