Dict already exists, and when I have a key
, check whether dict[key]
is None
or not, and
I thought it would work like the code below, but it didn't work, so I'm asking you a question.
if (my_dict[key] != None):
KeyError: 3
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
If my_dict[key]
finds a key that does not exist in dict (my_dict[key]
), None
is not returned, but KeyError
.
So the code is
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
If you change it like this, it will work as you want.
However, we recommend that you write collections.defaultdict because this is already a Python standard function.
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
578 Understanding How to Configure Google API Key
617 Uncaught (inpromise) Error on Electron: An object could not be cloned
911 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
610 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.