python – 从两个列表构建字典

参见英文答案 >
Convert two lists into a dictionary in Python                                    15个

我有两个列表,如下所示(长度相等)

cities = ['New York','Tokyo','Moscow','London']
altitudes = ['13000','12000','11000','9000']

我想构建一个字典如下

mydict = {x : y for x in cities and y in altitudes}

我的python解释器说无效的语法.为什么这个无效?我该怎么做?

最佳答案

thing = {city:altitude for city, altitude in zip(cities, altitudes)}

理解期望单个可迭代(列表等)循环.因此,要解决此问题,首先需要将两个列表转换为单个列表,然后将该列表提供给将其转换为dict的理解.

将上面的线分开一点,首先使用python的zip来聚合元素

list_of_tuples = zip(cities, altitudes)

然后你将其转换为dict:

thing = {city: alt for city, alt in list_of_tuples}

或者更简单

thing = dict(list_of_tuples)
点赞