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><em>I am assuming that in the <code>a_list</code>, one nested <code>list</code> will have same <code>'id'</code> and there will be only one list per id.</em></p>

<p>For achieving this, iterate over b_list and check for match in <code>a_list</code>. In case of match, add value to the dict object of <code>a_list</code></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;
&gt;&gt;&gt; for dict_item in b_list:
...     id = dict_item['post']
...     for list_item in a_list:
...         if list_item[0]['id'] == id:
...            dict_item['comments'] = list_item
...            break
...
&gt;&gt;&gt; b_list
[{
     'text': 'Something', 
     'post': '123', 
     'comments': [
         {
             'id': '123', 
             'user': 'Foo'
         }, 
         {
             'id': '123', 
             'user': 'Jonny'
         }
      ]
  }, 
  {
      'post': '456', 
      'text': 'Another thing', 
      'comments': [
         {
             'id': '456', 
             'user': 'Bar'
         }, 
         {
             'id': '456', 
             'user': 'Mary'
         }
      ]
   }
]
</code></pre>

python django list python-3.x dictionary