工作練手之玩蛇過程中遇到的小技巧(4)
阿新 • • 發佈:2018-12-13
列表解析式生成字典
場景:
看Python資料時學到了一種通過列表解析式生成字典的方式,工作暫未用到過,先記錄下來。
程式碼:
# 從 Python 2.7 開始,甚至可以用解析式生成字典(雜湊表) # Taken from page 70 chapter 3 of Fluent Python by Luciano Ramalho # 有如下列表,元素為多個tuple。 In [8]: DIAL_CODES = [ ...: (86, 'China'), ...: (91, 'India'), ...: (1, 'United States'), ...: (62, 'Indonesia'), ...: (55, 'Brazil'), ...: (92, 'Pakistan'), ...: (880, 'Bangladesh'), ...: (234, 'Nigeria'), ...: (7, 'Russia'), ...: (81, 'Japan'), ...: ] ...: # 通過列表解析式生成字典 In [9]: country_code = {country: code for code, country in DIAL_CODES} # 輸出字典 In [10]: country_code Out[10]: {'China': 86, 'India': 91, 'United States': 1, 'Indonesia': 62, 'Brazil': 55, 'Pakistan': 92, 'Bangladesh': 880, 'Nigeria': 234, 'Russia': 7, 'Japan': 81} # 還可以過濾條件生成字典 In [11]: {code: country.upper() for country, code in country_code.items() if code < 66} Out[11]: {1: 'UNITED STATES', 62: 'INDONESIA', 55: 'BRAZIL', 7: 'RUSSIA'}