user1862895
user1862895

Reputation: 93

How to get a dictionary from a list of dictionaries

I'm new to Python and stuck at something basic.

Say there's a list of dictionaries as follows:

[{key1:value1},{key2:value2},...{keyn:valuen}]

is there a pythonic way of extracting the dictionary

{key1:value1},{key2:value2},...{keyn:valuen}

Upvotes: 1

Views: 182

Answers (3)

Darknight
Darknight

Reputation: 1152

a=[{1:1},{2:2},{3:3}]

result=dict([(k,v) for x in a for k,v in x.items()])
print result //{1: 1, 2: 2, 3: 3}

Upvotes: 0

E.Z.
E.Z.

Reputation: 6661

Same thing, in perhaps an easier way to read:

result = {}
d_list = [{"key1": "value1"}, {"key2": "value2"}, {"keyn": "valuen"}]
for d in d_list:
    for k, v in d.iteritems():
        result[k] = v

Upvotes: 1

Blckknght
Blckknght

Reputation: 104722

I'm assuming you mean that you want {key1: value1, key2:value2, keyn:valuen}. That is, you want to combine all the separate dictionaries into a single one with each of the keys and values from the individual dictionaries.

Here's how I'd do it, using a dictionary comprehension:

 l = [{"key1":"value1"},{"key2":"value2"},{"keyn":"valuen"}]
 result = {k:v for d in l for k, v in d.iteritems()}

 print result # {'key2': 'value2', 'key1': 'value1', 'keyn': 'valuen'}

Upvotes: 5

Related Questions