【发布时间】:2016-10-06 23:35:20
【问题描述】:
我有两个列表。第一个(列表 a)包含 dicts 列表,每个列表代表来自特定帖子的 cmets。它们都具有相同的“id”值。第二个列表(列表 b)仅包含 dicts,这些 dicts 是帖子。
现在我需要为 b_list 中的每个 dict 创建名为“cmets”的新键,并将 a_list 中的适当列表分配为值。因此,目标列表是 dict['id'] 与 post 值相同的列表。
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'}, ...]
什么是最好的和更 Pythonic 的方式来做到这一点?
【问题讨论】:
-
你的意思是
b_list中的第一项应该转换成{'post':'123','text': 'Something', 'comments':[{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ...]}? -
正是@TigerhawkT3
-
a_list和b_list是否总是按照相应的顺序排列,第一个帖子 ID 是'123',然后是'456',等等? -
不,顺序可以不同
标签: python django list python-3.x dictionary