

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 提取字典的一部分


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
-
74
Python 中的字典操作
-
12
Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。 print(dir(dict)) ['clear', 'copy', 'fromkeys...
-
50
Python中的collections.defaultdict([default_factory[, … ]])在设置的字典key第一次出现的时候,自动调用default_factory方法创建一个默认的对象。这个类在实际使用中非常有用,可以帮助我们简化不少问题。 1.合并键...
-
35
△点击上方 “ Python猫 ”关注 ,回复“ 1 ”领取电子书
-
29
dict={'name':'Joe','age':18,'height':60}clear,清空dict.clear()#运行结果{}pop,移除指定key的键值对并返回vlaue(如果没有该key,可返回指定值),popitem,默认移除最后一个键值对print(dict.pop('age'))print(dict)#结果18,{'
-
7
一:字典 字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值 key=>value 对用冒号 : 分割,每个对之间用逗号( , )分割,整个字典包括在花括号 {} 中 ,格式如下所示:...
-
12
Fluent Python 笔记 —— 字典与集合 2020-11-08 ...
-
14
跟李宁老师学Python(6):Python字典-李宁-专题视频课程 ...
-
10
Python字典不是不可以排序,是你方法没用对!_李宁的极客世界bgJBm&nku$q$-CSDN博客摘要:排序是个古老的话题,不过对于字典的排序,常常会让 小白手足无措。好像没有找到可以排序字典的函数呢!到底是按key排序,还是按value排序呢?字典...
-
3
Jacky Liu September 7, 2022 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK