Python Dictionary Example
Tags: HashMap, python, python dictPython 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)
|
1 2 3 |
users = {'jim': ('Jim Lee', 'Male', 25), 'lina': ('Lina Green', 'Female', 32)} |
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’
|
1 2 |
print users['jim'] |
|
1 2 |
('Jim Lee', 'Male', 25) |
Key not exist exception
you may get key not exist exception when the username is not in the table
|
1 2 |
print users['user_x'] |
|
1 2 3 4 5 6 7 8 9 10 |
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-8-2052245cabb8> in <module>() ----> 1 print users['user_x'] KeyError: 'user_x' |
Do key check
We can get around this issue by an exist check
|
1 2 3 4 5 6 |
if 'user_x' in users: print users['user_x'] else: print 'user_x not exist' |
|
1 2 |
user_x not exist |
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
|
1 2 3 |
user_x = users.get('user_x', None) print user_x |
|
1 2 |
None |
|
1 2 3 |
user_lina = users.get('lina', None) print user_lina |
('Lina Green', 'Female', 32)











