【问题标题】:How to filter a dict to contain only keys in a given list? [duplicate]如何过滤字典以仅包含给定列表中的键? [复制]
【发布时间】:2011-10-13 06:12:41
【问题描述】:

对于 Python 和 stackoverflow 来说都是新手。感谢您的耐心等待和帮助。

我想根据列表的内容过滤一个字典,如下所示:

d={'d1':1, 'd2':2, 'd3':3}

f = ['d1', 'd3']

r = {items of d where the key is in f}

这很荒谬吗? 如果不是,正确的语法是什么?

感谢您的帮助。

文森特

【问题讨论】:

标签: python list dictionary filter


【解决方案1】:

假设您想创建一个新字典(无论出于何种原因):

d = {'d1':1, 'd2':2, 'd3':3}
keys = ['d1', 'd3']

filtered_d = dict((k, d[k]) for k in keys if k in d)
# or: filtered_d = dict((k, d[k]) for k in keys)
# if every key in the list exists in the dictionary

【讨论】:

  • dict 理解语法? python 2.7 和 3.x——更整洁!
  • @Felix Kling 我为一个字典d 尝试了这个,它有一个列表代替了值,它返回了一个空字典。如何相应地修改这几行?
  • @FrancescoCastellani:字典有哪些值并不重要:codepad.org/PyIJrdJF
  • 您认为这比for k in keys: filtered_d[k]=d[k] 更快吗?
  • filtered_d = {k:v for k,v in d.items() if k in d} -- 适用于那些寻找 dict comprehesion (dictcomp) 的人
【解决方案2】:

您可以使用列表推导遍历列表并在字典中查找键,例如

aa = [d[k] for k in f]

这是一个工作示例。

>>> d = {'k1': 1, 'k2': 2, 'k3' :3}
>>> f = ['k1', 'k2']
>>> aa = [d[k] for k in f]
>>> aa
[1, 2]

如果你想从结果中重建字典,你也可以在元组列表中捕获键并转换为字典,例如

aa = dict ([(k, d[k]) for k in f])

Python 的最新版本(特别是 2.7、3)有一个称为 dict comprehension 的功能,可以一键完成所有操作。更深入的讨论here.

【讨论】:

  • 非常相似,非常适合我,因为我不需要检查密钥的存在。非常感谢。
  • 假设 f 的所有元素都在 d 中。
  • 是的,如果字典中不存在某些内容,它将中断。另一篇文章中的一个 cmets 展示了一种使用 d.get(key) 的方法。
猜你喜欢
  • 2011-03-26
  • 2019-06-05
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
  • 2023-03-10
相关资源
最近更新 更多