码迷,mamicode.com
首页 > 编程语言 > 详细

【python cookbook】【数据结构与算法】16.从字典中提取子集

时间:2016-08-07 23:15:34      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

【python cookbook】【数据结构与算法】16.从字典中提取子集

标签:

原文地址:http://www.cnblogs.com/apple2016/p/5747573.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!