Remove entries of a dictionary that are not in a set

后端 未结 3 927
误落风尘
误落风尘 2021-01-15 08:04

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 remov

3条回答
  •  花落未央
    2021-01-15 08:50

    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.

提交回复
热议问题