Dictionary Functions
Deleting a Key¶
Using del followed by the dictionary indexed by a key will delete that key-value pair. The format of it is:
del dictionary[key]
In [10]:
#del deletes a key value pair
del name["Middle"]
print(name)
The len() function returns the number of pairs of keys and values.
In [11]:
#Len returns the number of pairs
print(len(name))
Checking Keys¶
If you want to check whether or not a key exists you can call the following and get back True/False:
key in dictionary
In [12]:
#If we ask if something is in a dictionary we check if it's in the keys
print('First' in name)
In [13]:
#Middle is not a key in the dictionary
print('Middle' in name)
This will NOT return whether or not a value is in the dictionary. Below we get back False because while it is a value it is not a key.
In [14]:
#John is a value in the dictionary but not a key, so we get false here
print('John' in name)
It can be checked in terms of whether or not it is in values by doing the same but modifying the dictionary to be dictionary.values()
In [15]:
#This will return true
print('John' in name.values())