Python Dictionary Example

Python dict structure is similiar to Java’s HashMap or HashTable.
It aims to store key value pairs.

Here is an example:
we build a dict to map a username to his profile information, which is a tuple

username => (Full_name, gender, age)

Search in Dict

Now we can do a look up by username with O(1) time complexity.
Search the user with username equal to ‘jim’

Key not exist exception

you may get key not exist exception when the username is not in the table

Do key check

We can get around this issue by an exist check

Use get with a default value

A better method is to use the get() method with default value.
If the key is not in the table, it will return a default value rather than throw an exception

('Lina Green', 'Female', 32)