Goran Goran - 6 months ago 27
Python Question

Python attach list of dict to another dict as new key

I have two lists. First one (list a) contain lists of dicts and every list represent comments from the specific post. They all have the same 'id' value. Second list (list b) contain dicts only and these dicts are posts.

Now I need to create new key named 'comments' for every dict in b_list and assign appropriated list from a_list as value. So targeted list is the one where dict['id'] are the same values as post value.

[{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ...],
[{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'}, ...],
b_list=[{'post':'123','text': 'Something'}, {'post':'456', 'text': 'Another thing'}, ...]

What will be the best and more pythonic way then to do that?


Build a dictionary of IDs and then go through them:

>>> a_list=[
...         [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ],
...         [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'},],
...        ]
>>> b_list=[{'post':'123','text': 'Something'}, {'post':'456', 'text':'Another thing'}, ]
>>> d = {l[0]['id']:l for l in a_list}
>>> for item in b_list:
...     item['comments'] = d[item['post']]
>>> import pprint
>>> pprint.pprint(b_list)
[{'comments': [{'id': '123', 'user': 'Foo'}, {'id': '123', 'user': 'Jonny'}],
  'post': '123',
  'text': 'Something'},
 {'comments': [{'id': '456', 'user': 'Bar'}, {'id': '456', 'user': 'Mary'}],
  'post': '456',
  'text': 'Another thing'}]