【Python学习】—字典推导式(dictionary comprehension)
目标:两个长度相同的list作为输入,返回一个字典,其中一个key,一个作为value:
def eg3_for(keys, values):
dic = {}
for i in range(len(keys)):
dic[keys[i]] = values[i]
return dic
def eg3_dc(keys, values):
return {keys[i]: values[i] for i in range(len(keys))}
country = ['India', 'Pakistan', 'Nepal', 'Bhutan', 'China', 'Bangladesh']
capital = ['New Delhi', 'Islamabad','Kathmandu', 'Thimphu', 'Beijing', 'Dhaka']
print(f"FOR-loop result: {str(eg3_for(country, capital))}")
print(f"DC result: {str(eg3_dc(country, capital))}")
输出:
FOR-loop result: {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}
DC result: {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}

浙公网安备 33010602011771号