获取字典的子集


prices = {
    "ACME": 45.23,
    "AAPL": 612.78,
    "IBM": 205.55,
    "HPQ": 37.20,
    "FB": 10.75
}

字典推导方式表意更清晰,并且实际上也会运行的更快些


这个比下面的要快
p1 = {key: value for key, value in prices.items() if value > 200}
print(p1)
# {'IBM': 205.55, 'AAPL': 612.78}

p1 = dict((key, value) for key, value in prices.items() if value > 200)
print(p1)
# {'IBM': 205.55, 'AAPL': 612.78}

tech_names = {"AAPL", "IBM", "HPQ", "MSFT"}

这个比下面的要快
p2 = {key: value for key, value in prices.items() if key in tech_names}
print(p2)
# {'HPQ': 37.2, 'IBM': 205.55, 'AAPL': 612.78}

p2 = {key: prices[key] for key in prices.keys() & tech_names}
print(p2)
# {'HPQ': 37.2, 'IBM': 205.55, 'AAPL': 612.78}