• Register

We can directly use the ‘in operator’ with the dictionary to check if a key exist in dictionary or nor. The expression,

key in dictionary

Will evaluate to a boolean value and if key exist in dictionary then it will evaluate to True, otherwise False. Let’s use this to check if key is in dictionary or not. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
}
key = 'test'
# python check if key in dict using "in"
if key in word_freq:
    print(f"Yes, key: '{key}' exists in dictionary")
else:
    print(f"No, key: '{key}' does not exists in dictionary")

Output:

Yes, key: 'test' exists in dictionary

Here it confirms that the key ‘test’ exist in the dictionary.

Now let’s test a negative example i.e. check if key ‘sample’ exist in the dictionary or not i.e.

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
}
key = 'sample'
# python check if key in dict using "in"
if key in word_freq:
    print(f"Yes, key: '{key}' exists in dictionary")
else:
    print(f"No, key: '{key}' does not exists in dictionary")

Output:

No, key: 'sample' does not exists in dictionary

Let’s suppose your dictionary key here will be ‘test’ and your list is stored in a variable named mylist

if ‘test’ in mylist :

this will check if it is in the list and you can continue your code however you want. Here’s an example below.

mylist = ['a','b','c','d'] 
dct = {'a':1, 'b':2, 'C':3, 'd':4, 'e':5} 
in_mylist = [] 
not_in_mylist = [] 
for each in dct: 
	if each in mylist: 
		in_mylist.append(each) 
	else: 
		not_in_mylist.append(each) 
print(in_mylist, not_in_mylist) 

 

1,760 points
6 1