views:

3430

answers:

4

Imagine that you have:

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')

What is the simplest way to produce the following dictionary ?

dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}

This code works, but I'm not really proud of it :

dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
+30  A: 

Like this:

>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print dictionary
{'a': 1, 'b': 2, 'c': 3}

Voila :-) The pairwise dict constructor and zip function are awesomely useful: http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#dict

Dan
Nice! I love it when a little piece of code makes me go "Ah-ha!" and puts a smile on my face...
Kevin Little
And thus begins the process of reshaping your brain to think "Pythonically", my young Padawan :-p
Dan
If the lists of keys and values are long, then itertools.izip or a generator expression should be used to avoid the resource cost of building a third list.
David Eyk
David, it's a good point. zip() is a bad idea with very long lists. Mike Davis's solution below uses izip() to avoid excessive copying and memory usage. For short lists, I don't worry.
Dan
+7  A: 
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}
iny
+8  A: 

Try this:

>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}

It was the simplest solution I could come up with.

--Mike Davis

PS It's also more economical in memory consumption compared to zip.

Mike Davis
You're not actually using itertools here.
Just Some Guy
You've managed to overwrite the builtin dict type so your example will only work once in program.
David Locke
My rust is showing.... Thanks for the edits and comments.
Mike Davis
+1  A: 

If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:

>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3]))

Take a look Code Like a Pythonista: Idiomatic Python.

J.F. Sebastian