删除不在集合中的字典条目 [英] Remove entries of a dictionary that are not in a set

查看:45
本文介绍了删除不在集合中的字典条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下字典和集合:

d = {1 : a, 2 : b, 3 : c, 4 : d, 5 : e }
s = set([1, 4])

我想知道是否可以删除集合中未包含的所有字典条目(即 2,3,5).我知道我可以通过遍历字典并检查每个键来实现这一点,但由于我是 Python 新手并且遇到了许多快捷方式",到目前为止我想知道是否存在针对此特定问题的快捷方式.

I was wondering if it is possible to remove all dictionary entries that are not contained in the set (i.e. 2,3,5). I am aware that i can achieve this by iterating over the dictionary and check each key but since i'm new to Python and came across many "shortcuts" so far I was wondering if there exists one for this particular problem.

推荐答案

d = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e' }
s = set([1, 4])

由于在迭代字典时不应该修改它,因此有两种可能来创建新字典.

Since you should not modify a dictionary while itering over it, you have two possibilities to create a new dictionary.

一种是从旧的过滤值中创建一个新的字典:

One is to create a new dictionary from the old one filtering values out:

d2 = dict((k,v) for k,v in d.iteritems() if k in s)

第二个是提取键,将它们与 s-set 相交并使用它们来构建一个新字典:

The second one is to extract the keys, intersect them with the s-set and use them to build a new dictionary:

d2 = dict((k, d[k]) for k in set(d) & s)

第三种是直接从d中移除元素:

The third one is to remove the elements directly from d:

for k in set(d) - s:
    del d[k]

这篇关于删除不在集合中的字典条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆