首页 > 编程 > Python > 正文

Python cookbook(数据结构与算法)从字典中提取子集的方法示例

2019-11-25 15:03:05
字体:
来源:转载
供稿:网友

本文实例讲述了Python从字典中提取子集的方法。分享给大家供大家参考,具体如下:

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

解决方案:利用字典推导式(dictionary comprehension)可轻松解决

# example of extracting a subset from a dictionaryfrom pprint import pprintprices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}# Make a dictionary of all prices over 200p1 = { key:value for key, value in prices.items() if value > 200 }print("All prices over 200")pprint(p1)# Make a dictionary of tech stockstech_names = { 'AAPL', 'IBM', 'HPQ', 'MSFT' }p2 = { key:value for key,value in prices.items() if key in tech_names }print("All techs")print(p2)

运行结果:

All prices over 200{'AAPL': 612.78, 'IBM': 205.55}All techs{'AAPL': 612.78, 'HPQ': 37.2, 'IBM': 205.55}

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

(代码摘自《Python Cookbook》)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字典操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表