我正在尝试使用map函数创建一个包含两个列表的字典。但是有些事情似乎不对。
我知道已经有zip和dict可以完成这项工作,但是我想知道为什么这段代码出错了,在哪里。
country = ['India', 'Pakistan', 'Nepal', 'Bhutan', 'China', 'Bangladesh']
capital = ['New Delhi', 'Islamabad','Kathmandu', 'Thimphu', 'Beijing',
'Dhaka']
country_capital={}
def mydict(x,y):
country_capital[x]=y
return country_capital
national_info=map(mydict,country,capital)
print (list(national_info))
为什么打印如下:
[{'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China':'Beijing', 'Bangladesh': 'Dhaka'}]
我想要这样:
[{'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}]
最佳答案
dict
接受两个元素的可迭代对象,因此您需要发出的所有内容是
country_capital = dict(zip(country, capital))
(由于某种原因,您的预期结果将这本词典包装在一个元素列表中。我看不出这样做的任何理由。)
关于python - 从列表创建字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48261843/