【发布时间】:2011-11-30 19:00:06
【问题描述】:
我有 2 个字典列表,比如说:
l1 = [{"customer":"amy", "order":2}, {"customer":"amy", "order":3}, {"customer":"basil", "order":4}]
l2 = [{"customer":"amy", "died":"who fell down the stairs"}, {"customer":'basil', "died":"assaulted by bears"}]
我正在寻找一种优雅的方式来从 l2 获取密钥并将它们放入 l1。这是为了加入使用不同值作为索引的字典列表
该函数应该类似于 join(l1,l2,'customer'),并生成
l3 = [{"customer":"amy", "order":2,"died":"who fell down the stairs"}, {"customer":"amy", "order":3,"died":"who fell down the stairs"}, {"customer":"basil", "order":4,"died":"assaulted by bears"}}]
l3 中的每个字典都应该有一个字典。
如果 l1 和 l2 具有相同的非连接键但值不同,则 l2 优先。
l2 将具有唯一的加入键值。
现在我已经尝试了这段丑陋的代码:
l3 = []
rdict = {}
for i in range(len(l2)):
rdict[l2[i][field]]=i
for d in l1:
l3.append(dict(d.items()+l2[rdict[d[field]]].items()))
return l3
和the solution from this SO question 一样,但假设所有列表中只有一个索引。
谢谢
【问题讨论】:
标签: python