Python将dict列表作为新键附加到另一个dict

2024-03-29 01:05:06 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

建立一个ID字典,然后检查它们:

>>> 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'}]

我假设在a_list中,一个嵌套的list将具有相同的'id',并且每个id只有一个列表。

为了实现这一点,迭代b_列表并检查a_list中的匹配。如果匹配,则向a_list的dict对象添加值

>>> 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'}]
>>>
>>> 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
...
>>> 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'
         }
      ]
   }
]

相关问题 更多 >