2

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

Community
  • 1
  • 1
Saurabh
  • 451
  • 2
  • 4
  • 18

3 Answers3

2

You could use a list comprehension:

data = [dict(itertools.izip(headers, entries)) for entries in values]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2
from functools import partial
from itertools import izip, imap
data = map(dict, imap(partial(izip, headers), values))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

It's already really nice...

data = [dict(itertools.izip(headers, entries) for entries in values]
tito
  • 12,990
  • 1
  • 55
  • 75