Remove entries of a dictionary that are not in a set

有些话、适合烂在心里 提交于 2020-12-26 03:49:42

问题


Given the following dictionary and set:

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

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.


回答1:


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)

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)

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

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



回答2:


Here are two nice solutions:

d = {1 : "a", 2 : "b", 3 : "c", 4 : "d", 5 : "e" }
keep_keys = set((1, 4))

# option 1, builds a new dictionary
d2 = {key:d[key] for key in set(d) & keep_keys}

# option 2, modifies the original dictionary
map(d.__delitem__, frozenset(d) - keep_keys)

If speed is what you want you should profile which one of the two are faster.




回答3:


Another solution:

d = {1 : "a", 2 : "b", 3 : "c", 4 : "d", 5 : "e" }
s = set([1, 4])
r = { k:d[k] for k in ( d.viewkeys() - s ) }


来源:https://stackoverflow.com/questions/9735504/remove-entries-of-a-dictionary-that-are-not-in-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!