如何从字典中删除其键是列表元素的所有元素?
[ 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 :
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.
You should be able to combine the two tasks.
for key in list_:
if key in dict_:
del dict_[key]
map(dictionary.__delitem__, lst)
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.
d = {'one':1, 'two':2, 'three':3, 'four':4}
l = ['zero', 'two', 'four', 'five']
for k in frozenset(l) & frozenset(d):
del d[k]
for i in lst:
if i in d.keys():
del(d[i])
我对Python一无所知,但是我想您可以遍历列表并通过字典中的键删除条目吗?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.