Operations on the dictionary
As you know, a dictionary is mutable; you can add new values, and delete and update old values. In this section, you will learn accessing, deletion, updation, and addition operations.
Accessing the values of dictionary
In order to access the dictionary's values you will need the key. Consider a dictionary of networking ports: In order to access the dictionary's values you will need the key. Consider a dictionary of networking ports:
Port = {80: “HTTP”, 23 : “Telnet”, 443 : “HTTPS”}
Let's learn by example:
>>> port = {80: "HTTP", 23 : "Telnet", 443 : "HTTPS"} >>> port[80] 'HTTP' >>> port[443] 'HTTPS'
In order to access the dictionary's value, use the square brackets along with the key. What happens if the key is not in the dictionary?
>>> port[21] Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> port[21] KeyError: 21 >>>
If the key is not found, then the interpreter shows the preceding...