在字典列表中合并不同的键 [英] Merging different keys inside a list of dictionaries
问题描述
如果这是一个重复的问题,我事先表示歉意,我非常努力地在Stack Overflow中找到它,但未成功. 我有一本字典,像一个风箱.
I apologize in advance if this is a repeated question, I tried very hard to find it in Stack Overflow, but I was not successful. I have a list of dictionaries like the one bellow.
d1 = {'saw': ['movie', '14', 'bird', '8', 'light', '5', 'plane', '4', 'man', '4'],
'saw': ['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5', 'pill', '4'],
'evicted': ['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'],
'evicted': ['dog', '9', 'teacher', '9', 'neighbor', '7', 'man', '6', 'girl', '6']}
我想根据它们的键合并不同的项目.这样它们看起来像:
I would like to merge different items,base on their key. So that they look like:
d2 = {'saw': ['movie', '14', 'bird', '8', 'light', '5',
'plane', '4', 'man', '4', 'zit', '10', 'popcorn', '6', 'pimple', '6',
'cherry', '5', 'pill', '4'],
'evicted': ['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4',
'dog', '9', 'teacher', '9', 'neighbor', '7', 'man', '6', 'girl', '6']}
我正在使用此代码,但没有所需的输出:
I am using this code, but it I am not having the desired the output:
d2 = {}
for d in d1:
for k, v in d1 ():
if k not in d2: d2 [k] = []
d2 [k].append (v)
print(d2)
我想当有两个单独的词典列表要合并时,这种方法会更好.如何在列表中合并不同的键?我真的很感谢任何帮助!
I guess this works better when there are two separate lists of dictionaries to merge. How to merge different keys inside a list? I really appreciate any help on this!
推荐答案
1.如果您的d1
是list
可以.但是,如果您的d1
是dict
,则dict
不能有重复的键.这是dict
的基本比例.因此您的d1
是非法的,将只有一个evicted
/saw
1.if your d1
is a list
it's ok. But if your d1
is a dict
, dict
cannot have duplicate keys. it is the basic proporty of dict
. so your d1
is illegal, will only have one evicted
/saw
2假设d1是一个列表,代码是:
2 assume d1 is a list the codes are:
for dicts in d1:
for key, value in dicts.items():
new_dict.setdefault(key,[]).extend(value)
这篇关于在字典列表中合并不同的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!