-1

I have a dictionary like below, as you see I am trying to print key_p which is not in dictionary. I want to check if my key_p exist in dictionary, print the value and when the key_p is not in dictionary print 0.

when I put condition elif, it will print two times 0 ( = the number of element in the dictionary) but I just want to check only key_p, meaning if the key_p is in the dictionary print 1 if only key_p is not in the dictionary print 0.

sc={'sen': 1,'lag': 1 }

key_p="tep"

for field, values in sc.items():

   if field==key_p:

      print("1")

   elif field!=key_p:

      print ("0")
Ma0
  • 14,712
  • 2
  • 33
  • 62
just
  • 1

2 Answers2

0

You can use in to check if key in dict.

Ex:

sc={'sen': 1,'lag': 1 }
if "tep" in sc:
    print("1")
else:
    print("0")

or if one line use dict.get.

Ex:

print(sc.get("tep", "0"))
Rakesh
  • 78,594
  • 17
  • 67
  • 103
0
sc={'sen': 1,'lag': 1 }

sc.get('tep') or '0'

#out
0
Roushan
  • 3,558
  • 3
  • 20
  • 37