Imagine that you have:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
What is the simplest way to produce the following dictionary?
a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
Imagine that you have:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
What is the simplest way to produce the following dictionary?
a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
The best solution is still:
Tranpose it:
If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:
Take a look Code Like a Pythonista: Idiomatic Python.
you can use this below code:
But make sure that length of the lists will be same.if length is not same.then zip function turncate the longer one.
Most performant - Python 2.7 and 3, dict comprehension:
A possible improvement on using the dict constructor is to use the native syntax of a dict comprehension (not a list comprehension, as others have mistakenly put it):
In Python 2,
zip
returns a list, to avoid creating an unnecessary list, useizip
instead (aliased to zip can reduce code changes when you move to Python 3).So that is still:
Python 2, ideal for <= 2.6
izip
fromitertools
becomeszip
in Python 3.izip
is better than zip for Python 2 (because it avoids the unnecessary list creation), and ideal for 2.6 or below:Python 3
In Python 3,
zip
becomes the same function that was in theitertools
module, so that is simply:A dict comprehension would be more performant though (see performance review at the end of this answer).
Result for all cases:
In all cases:
Explanation:
If we look at the help on
dict
we see that it takes a variety of forms of arguments:The optimal approach is to use an iterable while avoiding creating unnecessary data structures. In Python 2, zip creates an unnecessary list:
In Python 3, the equivalent would be:
and Python 3's
zip
merely creates an iterable object:Since we want to avoid creating unnecessary data structures, we usually want to avoid Python 2's
zip
(since it creates an unnecessary list).Less performant alternatives:
This is a generator expression being passed to the dict constructor:
or equivalently:
And this is a list comprehension being passed to the dict constructor:
In the first two cases, an extra layer of non-operative (thus unnecessary) computation is placed over the zip iterable, and in the case of the list comprehension, an extra list is unnecessarily created. I would expect all of them to be less performant, and certainly not more-so.
Performance review:
In 64 bit Python 3.4.3, on Ubuntu 14.04, ordered from fastest to slowest:
with Python 3.x, goes for dict comprehensions
More on dict comprehensions here, an example is there: