anon
anon

Reputation:

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}

Upvotes: 1

Views: 84

Answers (3)

Rocky Li
Rocky Li

Reputation: 5958

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

Upvotes: 2

fralau
fralau

Reputation: 3819

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.

Upvotes: 3

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

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.

Upvotes: 3

Related Questions