Dictionary Methods and Operations
Similar to lists and strings in Python, dictionaries also have built-in functions for insertion, deletion, updating elements, and other operations that need to be performed on dictionaries.
To get the total length of the dictionary, we use the len()
function. The total length of the dictionary is the number of items (or key-value pairs) in the dictionary. We saw this in strings and lists as well.
1student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2
3print(len(student))
To add new items in a dictionary, there is no built-in method. Rather, they are directly assigned by specifying the key name and its value with the dictionary as shown in the code block below.
1student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2
3student["section"] = "A"
4
5print(student) #prints the updated dictionary
Another important operation in dictionaries is the removal of items. This is performed by using the del
keyword by specifying the key name of the key-value pair with the dictionary name that needs to be removed.
1student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2
3del student["section"]
4
5print(student) #prints the updated dictionary
You can also remove the entire contents (all key-value pairs) of the dictionary using the dict.clear()
method.
1student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2
3student.clear()
4
5print(student) #prints the updated dictionary
Some more commonly used dictionary methods are,
- To get all the items or key-value pairs from the dictionary,
dict.items()
is used. It returns the key-value pairs in the form of a tuple. - To get all the keys in a dictionary,
dict.keys()
is used. This returns all the keys in the form of a list. dict.get(key)
returns a value for the specified key. If the key is not in the dictionary, the method returns None. This is an alternate method (other than indexing) to get values for a key in the dictionary.