本文實(shí)例講述了Python從字典中提取子集的方法。分享給大家供大家參考,具體如下:
問題:想創(chuàng)建一個(gè)字典,其本身是另一個(gè)字典的子集
解決方案:利用字典推導(dǎo)式(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)運(yùn)行結(jié)果:
All prices over 200{'AAPL': 612.78, 'IBM': 205.55}All techs{'AAPL': 612.78, 'HPQ': 37.2, 'IBM': 205.55}字典推導(dǎo)式的方案清晰且運(yùn)行起來很快。
(代碼摘自《Python Cookbook》)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python字典操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選