-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
  • 15,057
  • 4
  • 35
  • 65
just
  • 1
  • 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
  • 81,458
  • 17
  • 76
  • 113
0
sc={'sen': 1,'lag': 1 }

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

#out
0
Roushan
  • 4,074
  • 3
  • 21
  • 38
  • 1
    Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – Neuron Apr 16 '18 at 13:22