Reputation: 481
I want to map some values(a list of lists) to some keys(a list) in a python dictionary. I read Map two lists into a dictionary in Python
and figured I could do that this way :
headers = ['name', 'surname', 'city']
values = [
['charles', 'rooth', 'kentucky'],
['william', 'jones', 'texas'],
['john', 'frith', 'los angeles']
]
data = []
for entries in values:
data.append(dict(itertools.izip(headers, entries)))
But I was just wondering is there is a nicer way to go?
Thanks
PS: I'm on python 2.6.7
Upvotes: 2
Views: 1751
Reputation: 304195
from functools import partial
from itertools import izip, imap
data = map(dict, imap(partial(izip, headers), values))
Upvotes: 2
Reputation: 879591
You could use a list comprehension:
data = [dict(itertools.izip(headers, entries)) for entries in values]
Upvotes: 2
Reputation: 13251
It's already really nice...
data = [dict(itertools.izip(headers, entries) for entries in values]
Upvotes: 1