Reputation: 101
I have a dictionary and I want to delete each value of the dictionary which is the key.
I want this output: G = {'y': {'z'}, 'z': {'u', 'f', 'y'}, 'u': {'z'}}
G = {'y': {'z', 'y'}, 'z': {'z', 'u', 'f', 'y'}, 'u': {'u', 'z'}}
I tried this but I know. It's wrong.
for key,value in G.items():
if key == value:
del value
Upvotes: 2
Views: 85
Reputation: 164693
You aren't modifying the dictionary, but a variable value
. In addition, you don't want to look for equality of keys and values, you want to check if your key is in
your set value. Then remove it from your set via set.remove
. So you can use:
for key, value in G.items():
if key in value:
G[key].remove(key)
print(G)
{'y': {'z'}, 'z': {'u', 'y', 'f'}, 'u': {'z'}}
Alternatively, you can use set.discard
, which doesn't give KeyError
if the value does not exist in your set. The if
condition may therefore be omitted.
for key, value in G.items():
G[key].discard(key)
Finally, consider the below dictionary comprehension, which creates a new dictionary and assigns it to G
. This is not intrinsically inefficient: time complexity will be the same as the above methods. This version uses set.difference
, here via its syntactic sugar -
:
G = {k: v - {k} for k, v in G.items()}
As per @JonClements' comment, a one-line version which maintains references to G
is possible via dict.update
:
G.update({k: v - {k} for k, v in G.items()})
Upvotes: 4
Reputation: 11671
Delete the key in the value, not the value itself.
for key, value in G.items():
if key in value:
value.remove(key)
Upvotes: 0