开发者

Remove all elements from the dictionary whose key is an element of a list

开发者 https://www.devze.com 2023-01-24 10:33 出处:网络
How do you remo开发者_如何转开发ve all elements from the dictionary whose key is a element of a list?for key in list_:

How do you remo开发者_如何转开发ve all elements from the dictionary whose key is a element of a list?


for key in list_:
    if key in dict_:
        del dict_[key]


[Note: This is not direct answer but given earlier speculation that the question looks like homework. I wanted to provide help that will help solving the problem while learning from it]

Decompose your problem which is:

  1. How to get a element from a list
  2. How to delete a key:value in dictionary

Further help:

How do get all element of a list on python?

For loop works on all sequences and list is a sequence.

for key in sequence: print key

How do you delete a element in dictionary?

use the del(key) method.

  • http://docs.python.org/release/2.5.2/lib/typesmapping.html

You should be able to combine the two tasks.


map(dictionary.__delitem__, lst)


d = {'one':1, 'two':2, 'three':3, 'four':4}
l = ['zero', 'two', 'four', 'five']
for k in frozenset(l) & frozenset(d):
    del d[k]


newdict = dict(
    (key, value) 
    for key, value in olddict.iteritems() 
    if key not in set(list_of_keys)
)

Later (like in late 2012):

keys = set(list_of_keys)
newdict =  dict(
    (key, value) 
    for key, value in olddict.iteritems() 
    if key not in keys
)

Or if you use a 2.7+ python dictionary comprehension:

keys = set(list_of_keys)
newdict =  {
    key: value
    for key, value in olddict.iteritems() 
    if key not in keys
}

Or maybe even a python 2.7 dictionary comprehension plus a set intersection on the keys:

required_keys = set(olddict.keys()) - set(list_of_keys)
return {key: olddict[key] for key in required_keys}

Oh yeah, the problem might well have been that I had the condition reversed for calculating the keys required.


for i in lst:
    if i in d.keys():
        del(d[i])


I know nothing about Python, but I guess you can traverse a list and remove entries by key from the dictionary?

0

精彩评论

暂无评论...
验证码 换一张
取 消