Python ProgrammingPython Programming

Python check if a given key already exists in a dictionary

Example 1:

##
# Python's program to check if a given key already exists in a dictionary

x = {'z': 10, 'l': 50, 'c': 74, 'm': 12, 'f': 44, 'g': 19}

print(x)

if 'z' in x.keys():
    print("True")
else:
    print("False")

# Using ternary operator:
msg = "True" if 'z' in x else "False"
print(msg)


Sample output of above program.
C:\programs\dictionary>pep8 --first example1.py

C:\programs\dictionary>python example1.py
{'m': 12, 'g': 19, 'c': 74, 'l': 50, 'z': 10, 'f': 44}
True
True

C:\programs\dictionary>