SantoshGupta7
SantoshGupta7

Reputation: 6197

Is there a way to check if a dictionary has a key, and if that key's value is not None in one pass?

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

Answers (2)

Z4-tier
Z4-tier

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

John Zwinck
John Zwinck

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

Related Questions