Dictionary is one of the most popular data structures in Python. But what is it and how can we use it?
When you look for a word’s definition in any language like English, you open a dictionary (back in the old days of course) and find the meaning. The python dictionary is precisely like this. Dictionary in Python is a data structure made of key:value pairs. Each key brings us to a value directly. For example, a dictionary of a person’s data would be like this:
{“Name”: John, “Address”: XXX}
So when we want a person’s name, we can directly get it with the key “Name”.
Why do we need it?
The best point about dictionaries is the fast item access. When you have a list of values, the time complexity for finding a value is O(n) where n is the length of that list (unordered list). But in a dictionary, the same task time complexity is O(1) since we can directly jump to the value!
The way Python handles it is with a help of a list and a hash function. Python actually stores a dictionary as a list. So now the question is how can it directly find a list item? The answer is a hash function. The hash function gets a string as the input and returns an integer. So Python uses this as the mapper. For example, if the hash(“Name”) is 4, then the value for the key “Name” is at index 4 of the list.
Define a dictionary
There are three ways to define a dictionary in general. The first is to define an empty dictionary with help of dict() function in python and then add value to it:
d1 = dict()
d1['Name'] = "John"
d1['Address'] = "XXXY"
The second way is to initiate the dictionary while defining:
d2 = {"Name": "John", "Address": "XXX"}
The third way is with the help of the fromkeys function. This way is suitable when we want to create a dictionary with a list of keys and initiate all of them with a default value:
d3 = {}.fromkeys(["Name", "Address", "Phone"], "N/A")
Access
There are two general ways to access a dictionary value in Python. The first way is like list access where the index is the “key”:
d = {"Name": "John", "Address": "XXX"}
name = d["Name"]
# name is John
Downside: If the key does not exist, Python raises an exception.
The more secure way to access a value is the dictionary get() function. This function returns None instead of raising an exception if the key does not exist.
d = {"Name": "John", "Address": "XXX"}
name = d.get("Name")
Id = d.get("ID")
Id = d.get("ID", "Not There!")
# name is John and Id is None and Id is Not There!
Note: you can tell the get function to return any value instead of None when the key does not exist by providing a second parameter like get(“Name”, “Not There!”). If “Name” does not exist, Python returns “Not There!” instead of None.
Update
To update a value, we can just simply access it with the key and modify it:
d = {"Name": "John", "Address": "XXX"}
d['Name'] = "Salt"
# name is Salt!
The second way is the setdefault function. This function adds a new key:value if the key does not exist. If exists, it does nothing.
d = {"Name": "John", "Address": "XXX"}
d.setdefault("phone", "1235")
# phone is 1235!
The last update method is actually the update function. This is suitable when you want to update a dictionary with another dictionary.
d = {"Name": "John", "Address": "XXX"}
d.update({"phone": "12344", "City":"Berlin"})
# Now d also has a City and Phone!
Traverse
There are three general ways to traverse a dictionary. We can loop over the list of keys, values, and both of them at the same time.
To loop over keys, we use the keys() function:
d = {"Name": "John", "Address": "XXX"}
for key in d.keys():
print(key)
# Ouput: Name, Address
To loop over values, we use the values() function:
d = {"Name": "John", "Address": "XXX"}
for val in d.values():
print(val)
# Ouput: John, XXX
To loop over the pair of all key:value, we use the items() function:
d = {"Name": "John", "Address": "XXX"}
for key, val in d.items():
print(key + ":" + val)
# Ouput: Name:John, Address:XXX
Sorting
The last thing about a dictionary is sorting. The first approach is to use the sorted function in python. The result will be a sorted list of the dictionary keys.
d = {"a": 2, "b":-1, "c": 0}
print(sorted(d))
# output: ['a', 'b', 'c']
The second way is to sort the dictionary keys based on their value. To do this we use again the sorted function and the operator library.
import operator
d = {"a": 2, "b":-1, "c": 0}
s_d = dict(sorted(d.items(), key=operator.itemgetter(1)))
# Output: {'b': -1, 'c': 0, 'a': 2}
Note: the items() function returns all key:value pairs as a tuple where the itemgetter(1) is the value. The result of the sorting is a list of key:value tuples sorted by the value. This is the reason we cast it back to a dictionary with dict in python.
The full code is available here: https://github.com/Pooya-Oladazimi/blog-post-python/blob/master/dict.py
The End.
One thought on “How to use Dictionary in Python”
Comments are closed.