Reputation: 6197
sampleDict = {'1':None}
To check if a key exist, and if it's not None, I have to do this
if '1' in sampleDict:
if sampleDict['1'] is not None:
#do something
Is there a more pythonic way to do this in a single pass?
Upvotes: 0
Views: 1561
Reputation: 7988
If I take the question to mean exactly what it says ("check if a key exist, and if it's not None"), then you want dict.keys()
.
You must check if the key is not None
:
if key is not None:
do_something()
and that it exists:
if key is not None and key in my_dict.keys():
do_something()
Upvotes: -1
Reputation: 249502
Your code:
if '1' in sampleDict:
if sampleDict['1'] is not None:
#do something
Can be simplified to:
if sampleDict.get('1') is not None:
#do something
It subsumes the first if-clause by the fact that dict.get()
returns None
if not found. It subsumes the second if-clause by the fact that dict.get()
returns the same value as []
if the key is found.
Upvotes: 5