Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

python - 将两个列表转换成字典(Convert two lists into a dictionary)

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'}
  ask by Guido translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like this:

(像这样:)

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

The pairwise dict constructor and zip function are awesomely useful: https://docs.python.org/3/library/functions.html#func-dict

(成对的dict构造函数和zip函数非常有用: https : //docs.python.org/3/library/functions.html#func-dict)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...