I have this code in my script to perform Huffman encoding:
def huffmanEncoding(freqDict):
for key in freqDict.keys():
freqDict[HuffmanTree(value=key)] = freqDict.pop(key)
...
What I want to do is to replace each of the keys in the dictionary with a tree node whose value is the original key. The HuffmanTree class works properly.
However, this code has very weird behavior. With debugging tools I found out that sometimes some of the keys were processed twice or more times, which means they are first transformed into a tree node, then transformed again, using its current tree node as the value for the new tree node.
I replaced my code with the one shown following:
def huffmanEncoding(freqDict):
keys = list(freqDict.keys())
for key in keys:
freqDict[HuffmanTree(value=key)] = freqDict.pop(key)
and now it works properly. But can someone explain why my first version has such weird behavior? If I want to change all the keys in a dictionary, should I always use the second version?