Tutorial :Deleting from dict if found in new list in Python



Question:

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 dictionary?


Solution:1

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]"


Solution:2

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}  


Solution:3

dictionary = {1:3,4:5}  list = [1]    for key in list:    if key in dictionary:       del dictionary[key]  


Solution:4

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


Solution:5

A one liner to do this would be :

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


Solution:6

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.


Solution:7

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])  


Solution:8

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)  


Solution:9

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »