开发者

Deleting from dict if found in new list in Python

Say I have a dictionary with whatever number of values. And then I create a list. If any of the values of the list are found in the dictionary, regardless of whether or not it is a key or an index how do I delete the full value?

E.g:

dictionary = {1:3,4:5}
list = [1]
...
    dictionary = {4:5}

How do I do this without creating a new diction开发者_如何转开发ary?


for key, value in list(dic.items()):
    if key in lst or value in lst:
        del dic[key]

No need to create a separate list or dictionary.

I interpreted "whether or not it is a key or an index" to mean "whether or not it is a key or a value [in the dictionary]"


it's a bit complicated because of your "values" requirement:

>>> dic = {1: 3, 4: 5}
>>> ls = set([1])
>>> dels = []
>>> for k, v in dic.items():
    if k in ls or v in ls:
        dels.append(k)

>>> for i in dels:
    del dic[i]

>>> dic
{4: 5}


A one liner to do this would be :

[dictionary.pop(x) for x in list if x in dictionary.keys()]


dictionary = {1:3,4:5}
list = [1]

for key in list:
  if key in dictionary:
     del dictionary[key]


>>> dictionary = {1:3,4:5}
>>> list = [1]
>>> for x in list:
...     if x in dictionary:
...             del(dictionary[x])
... 
>>> dictionary
{4: 5}


def remKeys(dictionary, list):
    for i in list:
        if i in dictionary.keys():
            dictionary.pop(i)
    return dictionary


I would do something like:

for i in list:
    if dictionary.has_key(i):
         del dictionary[i]

But I am sure there are better ways.


A few more testcases to define how I interpret your question:

#!/usr/bin/env python

def test(beforedic,afterdic,removelist):
    d = beforedic
    l = removelist
    for i in l:
        for (k,v) in list(d.items()):
            if k == i or v == i:
                del d[k]

    assert d == afterdic,"d is "+str(d)

test({1:3,4:5},{4:5},[1])
test({1:3,4:5},{4:5},[3])
test({1:3,4:5},{1:3,4:5},[9])
test({1:3,4:5},{4:5},[1,3])


If the dictionary is small enough, it's easier to just make a new one. Removing all items whose key is in the set s from the dictionary d:

d = dict((k, v) for (k, v) in d.items() if not k in s)

Removing all items whose key or value is in the set s from the dictionary d:

d = dict((k, v) for (k, v) in d.items() if not k in s and not v in s)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜