python-進階教程-字典中提取子集
阿新 • • 發佈:2019-01-11
0.摘要
本文主要介紹從字典中提取子集的方法。
1.字典推導式(dictionary comprehension)
# example of extracting a subset from a dictionary from pprint import pprint prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } # Make a dictionary of all prices over 200 p1 = { key:value for key, value in prices.items() if value > 200 } print("All prices over 200") pprint(p1) #result:{'AAPL': 612.78, 'IBM': 205.55} # Make a dictionary of tech stocks tech_names = { 'AAPL', 'IBM', 'HPQ', 'MSFT' } p2 = { key:value for key,value in prices.items() if key in tech_names } print("All techs") pprint(p2) #result:{'AAPL': 612.78, 'HPQ': 37.2, 'IBM': 205.55}
2.利用元組序列構建新的字典
from pprint import pprint prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } # Make a dictionary of all prices over 200 p1 = dict((key, value)for key, value in prices.items() if value > 200) print("All prices over 200") pprint(p1) #result:{'AAPL': 612.78, 'IBM': 205.55}