[英]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 eg deleting 1 would make the Dictionary look like 我想从字典中删除1,这意味着键“ 1”以及其他键的值集中每次出现1的情况。例如,删除1会使字典看起来像
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. 首先从字典中删除该
item
,然后使用设置差异从值中删除所有出现的item
。
A simple not optimized one-liner to remove value
: 一个简单的,未经优化的单线去除
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! 编辑:感谢@mata的符号
{value}
,我总是忘记了!
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.