How to remove a value from a set that is inside a set dictionary?

Asked

Viewed 29 times

-1

For example, if I have a dictionary like this:

{
  x: { 1, 2, 3 },
  y: { 2, 3, 4 },
  z: { 1, 5, 6 }
}

How do I remove all occurrences of 2?

1 answer

0

Simply iterate through the sets, and remove the 2 of each.

dicionario = dict()

# Iniciando valores no dicionário
dicionario['x'] = set([1, 2, 3])
dicionario['y'] = set([2, 3, 4])
dicionario['z'] = set([1, 5, 6])

# Para cada conjunto...
for conjunto in dicionario.values():
    # Remova o valor 2
    conjunto.discard(2)

# Mostrar resultado
print(dicionario)

I used the method discard to the detriment of remove, for remove throws error when the item does not belong to the set. Already the discard does nothing, silently, which is the behavior we desire.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.