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 eg 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
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.
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!
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)
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.