Reputation: 93
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
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
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
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