You are trying to access a key that doesn't yet exist; your newDict
is empty.
If you wanted to populate newDict
with lists as the values, you need to first set the key to an empty list. Do so with dict.setdefault()
:
for key,value in oldDict.items():
if value compared to something else is true:
newDict.setdefault(key, []).append(value)
This sets key
to []
first, unless the key is already present in the dictionary.
However, since all keys in the old dictionary are unique, you may as well just use:
for key,value in oldDict.items():
if value compared to something else is true:
newDict[key] = [value]
That is, unless you were entirely confused and just wanted to set the value directly, and not create lists:
for key,value in oldDict.items():
if value compared to something else is true:
newDict[key] = value
Last but not least, you could create the new dictionary entirely in a dictionary comprehension:
def makeNewDictFromOld(oldDict):
return {key: value for key, value in oldDict.items()
if value compared to something else is true}