将词典列表合并到一个目录中

2024-05-15 04:57:43 发布

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

我有这个问题要解决。我试过很多方法。但却无法用最少的代码找出有效的方法

my_list = [{'qwerty': 'hello'},
           {'asdfg': 'watermelon'},
           {'asdfg': 'banana'}]

merge_list_of_dicts(my_list)

returns the below list.

[{'qwerty': ['hello']},
 {'asdfg': ['watermelon','banana']}]

Tags: ofthe方法代码hellomymergelist
3条回答

首先创建列表字典,然后附加原始数据中的值

奇怪的是,你想要一个字典列表而不是一本字典,所以我提供了两本

请尝试以下代码:

my_list = [{'qwerty': 'hello'},
           {'asdfg': 'watermelon'},
           {'asdfg': 'banana'}]

keys = set([list(i.keys())[0] for i in my_list])

dd = {k:[] for k in keys}

for d in my_list:
  dd[list(d.keys())[0]].append(list(d.values())[0])

print(dd)  # single dictionary

dd2 = [{x:dd[x]} for x in dd]

print(dd2)  # list of dictionaries

输出

{'qwerty': ['hello'], 'asdfg': ['watermelon', 'banana']}

[{'qwerty': ['hello']}, {'asdfg': ['watermelon', 'banana']}]

您没有告诉我们merge_list_of_dicts()内的内容,但实现此功能的一种方法是:

from collections import defaultdict

my_list = [{'qwerty': 'hello'},
           {'asdfg': 'watermelon'},
           {'asdfg': 'banana'}]


def merge_list_of_dicts(list_of_dicts: list) -> list:
    merged = defaultdict(list)
    for d in list_of_dicts:
        for key, value in d.items():
            merged[key].append(value)
    return [{k: v} for k, v in merged.items()]


print(merge_list_of_dicts(my_list))

产出:

[{'qwerty': ['hello']}, {'asdfg': ['watermelon', 'banana']}]

如果您向我们展示您实现的功能,那就更好了。一种直接的方法是遍历列表,然后遍历每个dict,然后将每个dict value:key添加到主dict中

mylist = [{"fruit" : "apple"}, {"drink" : "apple juice"}, {"meals" : ["apple pies", "apple salad"]}]
newdict = {}
for dictionary in mylist:
    for key in dictionary:
        newdict[key] = dictionary[key]

print(newdict)

相关问题 更多 >

    热门问题