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'}
For those who need simple code and aren’t familiar with
zip
:This can be done by one line of code:
Try this:
In Python 2, it's also more economical in memory consumption compared to
zip
.You can make it with one line using dictionary comprehension:
and thats it .Enjoy Python.....;)
method without zip function
Like this:
Voila :-) The pairwise
dict
constructor andzip
function are awesomely useful: https://docs.python.org/3/library/functions.html#func-dictYou can also use dictionary comprehensions in Python ≥ 2.7: