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

 

posted @ 2022-03-17 22:43  易点灵通  阅读(315)  评论(0)    收藏  举报