Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Key exists in nullable dict in python3

I have a python dictionary object that will get value by a user. Also the user may leave it as None.

I want to check if my dict has a specific key or not, I tried if key in dict but I got argument of type 'NoneType' is not iterable error when my dict is None.

I need one line statement that returns False either my dict is None or my dict does not have that key.
Here is my code: (form is the dictionary)

if 'key' not in form:
    # Do somethin

Upvotes: 0

Views: 148

Answers (6)

mhawke
mhawke

Reputation: 87074

Not sure why you must have a one-liner, but this is one:

False if d is None or k not in d else d[k]

Or (thanks @Chris_Rands for the hint)

False if not d else d.get(k, False)

If you simply want to test if the dict contains the key:

k in d if d else False

Upvotes: 2

Kenny Aires
Kenny Aires

Reputation: 1438

Try to add the one line statement as follows:

True if dict and key in dict else False;

So then, returns False either dict is None or dict does not have that key.

Upvotes: 1

shanmuga
shanmuga

Reputation: 4499

One liner for checking not None and key presence. I assume my_dict has the values from user

result = (my_dict is not None) and (key in my_dict)

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51643

You can use a ternary togetether with dict.get(key, default):

d = None
k = d.get("myKex", False) if d else False  # dicts that are None are "False"

d = {2 : "GotIt"}
k2 = d.get("2", False) if d else False     # get() allows a default if key not present
k3 = d.get(2, False) if d else False       # got it ...


print (k, k2, k3)

Output:

(False, False, 'GotIt')

Further reading:

Upvotes: 2

rahul mehra
rahul mehra

Reputation: 438

Try this:

if dict.has_key('specific-key-name-here'):

Upvotes: -1

shahaf
shahaf

Reputation: 4973

if dict is not None:
  if key in dict.keys():
    return True
return False

Upvotes: 0

Related Questions