Delete value from a Python dictionary

Asked

Viewed 5,301 times

0

I need to delete a key from a dictionary if a certain situation arises. I have this code:

for i in dict.keys(dataClean):
     dataClean[i] = dataClean[i] - 1
     if dataClean[i] == 0:
          del dict.keys(dataClean[i]) # remover i do dataClean

But the last line doesn’t work that way. How it should be done?

2 answers

3


To remove a dictionary value, it is not done the way it was trying to accomplish:

del dict.keys(dataClean[i]) # remover i do dataClean

It is held this way:

del dataClean[i]

However, performing an iterable removal during its execution will present the following error::

File ".../del-dict-element.py", line 11, in <module>
for i in dict.keys(dataClean):

Followed by his exception:

RuntimeError: dictionary changed size during iteration

The Python has a feature that removes the desired item, the pop():

dictionary.pop(keyname, defaultvalue)

However, it follows an intuitive version for your code:

dicionario = {
    'dois': 2,
    'tres': 3,
    'quatro': 4,
    'cinco': 5,
    'seis': 6,
    'sete': 7,
    'baguncado': 1,
    'outro baguncado': 1
}

remover_itens = []

for chave, valor in dicionario.items():
    dicionario[chave] = dicionario[chave] -1
    if dicionario[chave] == 0:
        remover_itens.append(chave)

for item in remover_itens:
    dicionario.pop(item)

print(dicionario)

input: {'dois': 1, 'tres': 2, 'quatro': 3, 'cinco': 4, 'seis': 5, 'sete': 6, 'baguncado': 0, 'outro baguncado': 0}

output: {'dois': 1, 'tres': 2, 'quatro': 3, 'cinco': 4, 'seis': 5, 'sete': 6}

2

It is not a good idea to remove keys from an eternity while you walk through it, use list comprehension for that case. Example:

dic = {
    'a': 13,
    'b': 0,
    'c': 52,
    'd': 0,
    'e': 0,
    'f': 79
}

newDic = { key: dic[key] for key in dic if dic[key] != 0 }

print(newDic)
# {'a': 13, 'c': 52, 'f': 79}

Browser other questions tagged

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