Convert two lists into a dictionary in Python

2018-12-31 01:25发布

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'}

13条回答
笑指拈花
2楼-- · 2018-12-31 01:56

For those who need simple code and aren’t familiar with zip:

List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']

This can be done by one line of code:

d = {List1[n]: List2[n] for n in range(len(List1))}
查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 02:00

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'}

In Python 2, it's also more economical in memory consumption compared to zip.

查看更多
路过你的时光
4楼-- · 2018-12-31 02:02

You can make it with one line using dictionary comprehension:

a_dict={key:value for key,value in zip(keys,values)}

and thats it .Enjoy Python.....;)

查看更多
梦醉为红颜
5楼-- · 2018-12-31 02:06

method without zip function

l1 = {1,2,3,4,5}
l2 = {'a','b','c','d','e'}
d1 = {}
for l1_ in l1:
    for l2_ in l2:
        d1[l1_] = l2_
        l2.remove(l2_)
        break  

print (d1)


{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}
查看更多
余生请多指教
6楼-- · 2018-12-31 02:08

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: https://docs.python.org/3/library/functions.html#func-dict

查看更多
时光乱了年华
7楼-- · 2018-12-31 02:09

You can also use dictionary comprehensions in Python ≥ 2.7:

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> {k: v for k, v in zip(keys, values)}
{'food': 'spam', 'age': 42, 'name': 'Monty'}
查看更多
登录 后发表回答