简体   繁体   English

如何从单个字典创建字典列表?

[英]How to create list of dictionaries from a single dictionary?

How can I turn a list of dictionaries into a single dictionary?如何将字典列表转换为单个字典?

For example, let's say my initial list is as:例如,假设我的初始列表如下:

Dictionary_list = [{key:value}, {key2:value2}, {key3:value3}]

I need the resultant dictionary as:我需要结果字典为:

New_dictionary = {key:value, key2:value2, key3:value3}

You may use dictionary comprehension to achieve this as:您可以使用字典理解来实现这一点:

>>> my_list = [{'key':'value'}, {'key2':'value2'}, {'key3':'value3'}]

>>> my_dict = {k: v for item in my_list for k, v in item.items()}
>>> my_dict
{'key3': 'value3', 'key2': 'value2', 'key': 'value'}

Note: If your initial list of dictionaries will have any "key" present in more than one dictionary, above solution will end up keeping the last "value" of "key" from the initial list.注意:如果您的初始字典列表中存在多个字典中的任何“键”,则上述解决方案最终将保留初始列表中“键”的最后一个“值”。

Another solution would be to create an empty dictionary and update it:另一种解决方案是创建一个空字典并更新它:

>>> my_list = [{'key':'value'}, {'key2':'value2'}, {'key3':'value3'}]
>>> my_dict = {}
>>> for d in my_list: my_dict.update(d)
...
>>> my_dict
{'key': 'value', 'key2': 'value2', 'key3': 'value3'}

In general, the update() method is mighty useful, typically when you want to create "environments" containing variables from successive dictionaries.通常, update() 方法非常有用,通常当您想要创建包含来自连续字典的变量的“环境”时。

Functional programming answer:函数式编程答案:

from functools import reduce # depending on version of python you might need this. 

my_list = [{'key':'value'}, {'key2':'value2'}, {'key3':'value3'}]
def func(x,y):
    x.update(y)
    return x
new_dict = reduce(func, my_list)

>>> new_dict
{'key': 'value', 'key2': 'value2', 'key3': 'value3'}

One liner:一个班轮:

new_dict = reduce(lambda x, y: x.update(y) or x, my_list) # use side effect in lambda

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM