domoarigato
domoarigato

Reputation: 2912

turn tuple of dicts into single dict

I have data:

({'name': 'bob', 'sex': 'male'}, {'name': 'sally', 'sex': 'female'})

I want to have

{'bob': 'male', 'sally': 'female'}

Whats a fast, easy way to do it? The data is always n-length tuple of dicts with the same key/value pair.

Upvotes: 0

Views: 203

Answers (2)

Neal Miller
Neal Miller

Reputation: 196

x = ({'name': 'bob', 'sex': 'male'}, {'name': 'sally', 'sex': 'female'})

print {y['name']:y['sex'] for y in x} 

>> {'bob': 'male', 'sally': 'female'}

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121594

You use a dict comprehension:

{d['name']: d['sex'] for d in input_structure}

This produces one dictionary where the keys and values are taken from the two keys in the input dictionaries.

If you are using Python 2.6 or older, you'll have to resort to a dict() call with generator expression instead:

dict((d['name'], d['sex']) for d in input_structure)

Demo:

>>> sample = ({'name': 'bob', 'sex': 'male'}, {'name': 'sally', 'sex': 'female'})
>>> {d['name']: d['sex'] for d in sample}
{'bob': 'male', 'sally': 'female'}
>>> dict((d['name'], d['sex']) for d in sample)
{'bob': 'male', 'sally': 'female'}

Upvotes: 3

Related Questions