《流畅的python》:生成字典的几种方式

a =dict(one=1,two=2,three=3)
b = {'one':1,'two':2,'three':3}
c = dict(zip(['one','two','three'],[1,2,3]))
d = dict([('one', 1), ('two', 2), ('three', 3)])
e = dict({'one': 1, 'two': 2, 'three': 3})
print(a==b==c==d==e)

 字典推到也可以生成字典:可以从任何以键值对作为元素的可迭代对象中构建字典:

DATL_CODES = [
    (86,'CHINA'),
    (91,'India'),
    (1,'United States'),
    (62,'Indonesia'),
    (55,'Brazil')
]
country_code = {country:code for code,country in DATL_CODES}
print(country_code)

code_country = {code:country.upper() for country,code in country_code.items() if code < 66}
print(code_country)

 

posted @ 2020-10-29 09:27  沧海1024  阅读(435)  评论(0编辑  收藏  举报