gpt4 book ai didi

python - 将字典列表合并为一个字典,并将项目附加到列表

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:14 25 4
gpt4 key购买 nike

def merge_dicts(list_of_dicts: list, missval=None):
'''Merges a list of dicts, having common keys into a single dict
with items appended to a list

>>> d1 = {'a' : 1, 'b': 2, 'c': 3}
>>> d2 = {'a':4, 'b':5 }
>>> d3 = {'d': 5}
>>> merge_dicts([d1, d2, d3], 'NA')
{'a': [1, 4, 'NA'], 'b': [2, 5, 'NA'],
'c': [3, 'NA', 'NA'], 'd': ['NA', 'NA', 5]}
'''
all_keys = []
for d in list_of_dicts:
for k in d.keys():
if k not in all_keys:
all_keys.append(k)

merged = {}
for k in all_keys:
for d in list_of_dicts:
try:
merged[k].append(d.get(k, missval))
except KeyError:
merged[k] = [d.get(k)]

return(merged)

函数文档字符串是不言自明的。有没有更有效的方法来做到这一点而不必编写两个 for 循环?一个是找到所有字典中的所有键,另一个是合并字典?

最佳答案

如果您不关心它们的顺序,您应该使用set 来创建键列表。您可以使用理解来创建它。

对于第二部分,您可以使用字典理解,并使用列表理解创建每个列表:

def merge_dicts(list_of_dicts: list, missval=None):
'''Merges a list of dicts, having common keys into a single dict
with items appended to a list

>>> d1 = {'a' : 1, 'b': 2, 'c': 3}
>>> d2 = {'a':4, 'b':5 }
>>> d3 = {'d': 5}
>>> merge_dicts([d1, d2, d3], 'NA')
{'a': [1, 4, 'NA'], 'b': [2, 5, 'NA'],
'c': [3, 'NA', 'NA'], 'd': ['NA', 'NA', 5]}
'''
all_keys = {key for d in list_of_dicts for key in d.keys()}
merged = {k: [d.get(k, missval) for d in list_of_dicts] for k in all_keys}

return(merged)


d1 = {'a' : 1, 'b': 2, 'c': 3}
d2 = {'a':4, 'b':5 }
d3 = {'d': 5}
merge_dicts([d1, d2, d3], 'NA')


#{'a': [1, 4, 'NA'],
# 'b': [2, 5, 'NA'],
# 'c': [3, 'NA', 'NA'],
# 'd': ['NA', 'NA', 5]}

关于python - 将字典列表合并为一个字典,并将项目附加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com