本文實(shí)例講述了Python從字典中提取子集的方法。分享給大家供大家參考,具體如下:
問(wèn)題:想創(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)行起來(lái)很快。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選