提取字典的子集

有时候,需要根据已知的字典对象构造一个新的字典对象。这种场景可以使用字典生成式(dictionary comprehension)。如下:

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}

# 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}

同样,也可以使用dict的构造函数,如下:

p1 = dict((key, value) for key, value in prices.items() if value > 200)

然而,使用字典生成式更清晰,实际运行速度要快得多(在示例中使用的字典上测试时速度快两倍)。
下面是另一种示例:

# Make a dictionary of tech stocks
tech_names =  { 'AAPL', 'IBM', 'HPQ', 'MSFT' }
p2 = { key:prices[key] for key in prices.keys() & tech_names }
posted @ 2019-08-07 14:07  Jeffrey_Yang  阅读(273)  评论(0编辑  收藏  举报