Python attach list of dict to another dict as new key
<p>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.</p>

<p>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. </p>

<pre><code>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'}, ...]
</code></pre>

<p>What will be the best and more pythonic way then to do that?</p>

<p>Build a dictionary of IDs and then go through them:</p>

<pre><code>&gt;&gt;&gt; a_list=[
...         [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ],
...         [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'},],
...        ]
&gt;&gt;&gt; b_list=[{'post':'123','text': 'Something'}, {'post':'456', 'text':'Another thing'}, ]
&gt;&gt;&gt; d = {l[0]['id']:l for l in a_list}
&gt;&gt;&gt; for item in b_list:
...     item['comments'] = d[item['post']]
...
&gt;&gt;&gt; import pprint
&gt;&gt;&gt; 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'}]
</code></pre>

python django list python-3.x dictionary