I have following data structure
>>> a = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}]
>>> b = [{'id': 1, 'age': 12}, {'id': 2, 'age': 21}]
I want to merge the dictionaries present in list b with list a by matching id. (a
and b
have the same number of entries, but the order can be different.)
So I want following:
[{'age': 12, 'id': 1, 'name': 'a'}, {'age': 21, 'id': 2, 'name': 'b'}]
I am doing it by following:
>>> for ta in a:
... for tb in b:
... if ta['id'] == tb['id']:
... ta.update(tb)
...
>>> a
[{'age': 12, 'id': 1, 'name': 'a'}, {'age': 21, 'id': 2, 'name': 'b'}]
>>>
Is there a better Pythonic way of doing it?
a
andb
come in an arbitrary order? Are the list lengths the same? Please come up with a richer example to more clearly illustrate the desired behaviour. \$\endgroup\$a
andb
come from? An SQL database? A CSV file? \$\endgroup\$