Ad Code

Ticker

6/recent/ticker-posts

How to check key exists in python dictionary

Python dictionary is an unordered collection of items and its work on key => value pair of data, optimizes and retrieves its values when the key is known.

How to check key exists in python dictionary

Python dictionary format:-
exampledict = {} //blank dictionary initialize

exampldict2 = {"key1":"value1","key2":"value2"} //create dictionary with existing items

Check dictionary key exists:-
method 1:-
if 'key1' in exampledict2:
    print('key1 exist')
else:
    print('key1 not exist')
method 2 (if you want to set default value or reference value assign then use this way):-
status = 'Active' if 'key' in exampledict2 else 'Deactive'

Post a Comment

0 Comments

Ad Code