Having an item in a dictionary in Python
You can check the presence of a key in a dictionary using the in operator, and its absence using not in.
Let's see in practice. Let's say we have the following dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's check if there is an element with key 'a' in the dictionary:
print('a' in dct) # True
Let's check that there is no element in the dictionary with the key 'x':
print('x' not in dct) # True
Given a dictionary:
dct = {
'x': 1,
'y': 2,
'z': 3
}
Check if it contains an element with key 'w'.
The following code is given:
dct = {
1: 'x',
2: 'y',
3: 'z',
4: 'w'
}
print('x' in dct)
Tell me what will be output to the console.
The following code is given:
dct = {
1: 'x',
2: 'y',
3: 'z',
4: 'w'
}
print('x' not in dct)
Tell me what will be output to the console.
The following code is given:
dct = {
1: 'x',
2: 'y',
3: 'z',
4: 'w'
}
print(3 in dct)
Tell me what will be output to the console.