0
Python 提取字典的一部分
source link: https://www.lfhacks.com/tech/subdictionary-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python 提取字典的一部分
扫一扫,转发文章
本文发布至今已有7年零232天,可能不再适用,请谨慎对待。
Python如何提取提取字典的一部分,即子字典(sub-dictionary)?
比如已有字典
{'A':1, 'B':2, 'C':3, 'D':4, 'E':5}
['C', 'E']
{'C':3, 'E':5}
可以用以下方法提取子字典:
base = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5}subkey = ['C', 'E']print(dict([(key, base[key]) for key in subkey])) #{'C': 3, 'E': 5}
Python总有不止一种办法解决问题:
使用dict comprehension
base = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5}subkey = ['C', 'E']print({key:base[key] for key in subkey}) #{'C': 3, 'E': 5}
使用unpack
base = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5}subkey = ['C', 'E']print({k:v for k,v in base.items() if k in subkey}) #{'C': 3, 'E': 5}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK