问题:想创建一个字典,其本身是另一个字典的子集

解决方案:利用字典推导式(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)

# 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)
>>> ================================ RESTART ================================
>>> 
All prices over 200
{'AAPL': 612.78, 'IBM': 205.55}
All techs
{'AAPL': 612.78, 'HPQ': 37.2, 'IBM': 205.55}
>>> 

字典推导式的方案清晰且运行起来很快。

相关文章:

  • 2021-12-16
  • 2022-01-28
  • 2021-08-29
  • 2021-07-09
  • 2022-02-16
  • 2022-02-08
  • 2021-04-21
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-28
  • 2021-09-26
  • 2021-11-03
  • 2022-01-17
  • 2021-12-30
  • 2021-12-18
相关资源
相似解决方案