是否可以只使用字典中的.get()
函数?这是我们能做的最好的缩短这段代码的方法吗?
n_dict
是Dict
类型(大写D
(,NES
只是str
的列表
eted_info = {}
for key in n_dict:
if key in NES:
eted_info[key] = n_dict[key]
我只是想知道是否有一种更好/更像Python的方法来检索值,就像C#使用TryGetValue
一样。
我认为字典理解和使用n_dict.items()
是完成的最干净的方法
n_dict = {'a': 1, 'b': 2, 'c': 3}
NES = ['a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
eted_info = {key:value for key,value in n_dict.items() if key in NES}
print(eted_info)
结果
{'a': 1, 'c': 3}
你可以用字典理解做一些事情,比如:
eted_info = {key: n_dict[key] for key in n_dict if key in NES}
如果您想避免对NES
中的每个项对n_dict
中的每个项目进行迭代的O(n^2(操作,您可以构建一个密钥列表作为set
交集,并对其进行迭代:
eted_info = {k: n_dict[k] for k in set(n_dict) & set(NES)}
在NES
中的键上迭代;使用默认为None
的n_dict.get.get
;有条件地添加到CCD_ 15。
for key in NES:
v = n_dict.get(key,None)
if v: eted_info[key] = v
- 无论n_dict的长度如何,这只会在列表上迭代一次
- 假设
n_dict
中的所有值都是真实的。其他占位符可用于默认值