简体   繁体   English

从字典中删除其键是列表元素的所有元素

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

如何从字典中删除其键是列表元素的所有元素?

[ 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? 如何在python上获取列表的所有元素?

For loop works on all sequences and list is a sequence. For循环适用于所有序列,而list是一个序列。

for key in sequence: print key

How do you delete a element in dictionary? 如何删除字典中的元素?

use the del(key) method. 使用del(key)方法。

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): 之后(例如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: 或者,如果您使用2.7+ python字典理解:

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: 或者甚至是python 2.7字典理解以及在键上设置了交集:

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一无所知,但是我想您可以遍历列表并通过字典中的键删除条目吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM