Bis_86
Bis_86

Reputation: 23

Deleting a Key and its occurrence in other key's Value in python dictionary

Suppose I have a dictionary

myDict={0: set([1]),1: set([0, 2]),2: set([1, 3]),3: set([2])}

and I want to delete 1 from the dictionary ,that means the key "1" and every occurence of 1 in sets of value of other Key .For e.g deleting 1 would make the Dictionary look like

myDict={0: set([]),2: set([ 3]),3: set([2])}

I am trying to achieve this but not able to do so .Thanks in advance

Upvotes: 1

Views: 67

Answers (3)

Lafexlos
Lafexlos

Reputation: 7735

del myDict[item]
for key, value in myDict.items():
    if item in value:
        myDict[key] = value.difference(set([item]))

You can use something like this. First remove the item from dictionary, then remove all occurances of it from values using set difference.

Upvotes: 2

Seb D.
Seb D.

Reputation: 5195

A simple not optimized one-liner to remove value:

{k : v - {value} for k, v in myDict.items() if k != value}

Edit: thanks to @mata for the notation {value}, I always forget it!

Upvotes: 2

shaktimaan
shaktimaan

Reputation: 1857

val = 1
if val in myDict:
    del myDict[val]
for key in myDict.keys():
   if  isinstance( myDict[key], set) and val in myDict[key]:
        myDict[key].remove(val)

Upvotes: 1

Related Questions