0

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
Mehrdad Pedramfar
  • 9,313
  • 3
  • 31
  • 54
  • 2
    can you please show us your code? Also do not use names that Python already uses like `dict`. Name your dicts something else – Ma0 Mar 28 '18 at 09:55
  • simply check first before iteration if dict: print("True"). – Mirza715 Mar 28 '18 at 10:01

6 Answers6

2

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
mhawke
  • 75,264
  • 8
  • 92
  • 125
2

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:

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
1

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)
shanmuga
  • 3,667
  • 2
  • 16
  • 33
1

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.

Kenny Aires
  • 743
  • 7
  • 13
0
if dict is not None:
  if key in dict.keys():
    return True
return False
shahaf
  • 3,828
  • 2
  • 22
  • 31
-1

Try this:

if dict.has_key('specific-key-name-here'):
rahul mehra
  • 392
  • 1
  • 12