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}