How to create a dictionary with ordered and read-only items, returning default value with non-existent key, grouping multiple dictionaries into a single map and much more
You may be familiar with a dictionary in Python, that allows for the efficient lookup, insertion, and deletion of any value associated with a given key. To put in simple words, imagine going to a grocery store, if you want to find out the price of an item, you just need to input the name of the item and the price associated with the item will be returned immediately
food = {<br> 'fish': 10,<br> 'broccoli': 3,<br> 'tofu': 5,<br> 'mushroom': 3<br>}<br>food['fish']
Outcome: 10 But what if you want your dictionary to behave in a particular way that it would take some thoughts to implement? Let’s look at 4 different scenarios when you want your dictionary to have a specialized implementation, such as:Create an ordered dictionaryReturn the default values when there is no requested keyGroup multiple dictionaries into a single mappingCreate a read-only dictionary
Create an Ordered Dictionary
Scenario:
You want to use a dictionary to organize the tasks that you want to finish for the weekend, whose keys are the tasks and values are the hours to complete the task. Since you want to finish the tasks in the order of input, you don’t want the dictionary to mix up the order of your tasks, you decide to use OrderedDict
OrderDict
collections.OrderedDict is ideal if key order is important for your goal.
tasks = collections.OrderedDict(laundry=0.5, shopping=2, clean=2)
Outcome:
OrderedDict([('laundry', 0.5), ('shopping', 2), ('clean', 2), ('movie', 2)])
odict_keys(['laundry', 'shopping', 'clean', 'movie'])
As we can see, the items in the list are listed in the order of input. Now you just need to follow your dictionary to finish your weekend tasks in the right order.
Return the Default Value when There is no Requested Key
ScenarioYou want to create a dictionary that maps the classes to the room number. Since many classes are taught outside (because the weather is nice), you don’t want to take the time to map those classes to the Outside value. You decide to use Defaultdict.
Defaultdict
collections.Defaultdict can be initialized with a function that takes no arguments and provides the default value if a requested key cannot be found.
from collections import defaultdict
classes = defaultdict(lambda: 'Outside')
classes['Math'] = 'B23'<br>classes['Physics'] = 'D24'
Outcome: B23 . Defaultfict behaves just like a standard dictionary, except it allows the value of non-existence key to return
Outcome: OutsideThe default value that we specified is returned when the non-existence key is provided. Now you don’t need to take the time to map 20 classes that are taught outside to Outside values.
Group Multiple Dictionaries into a Single MappingScenario:
You want to take note of the lists of your friends and their information. Each friend’s information will be represented as a dictionary with name and age. Once you have the information on all of your friends, you contemplate how to put all that information together into a single place. You discover ChainMap .
ChainMap
collections.ChainMap behaves like its name. The data structure allows you to group multiple dictionaries together like a chain.
from collections import ChainMap
#Create multiple dictionaries of friends and their information
friend1 = {'name':'Ben','age':23}<br>friend2 = {'name':'Thinh', 'age': 25}
#Group these dictionaries together
friends = ChainMap(friend1, friend2)<br>friends
Outcome:
ChainMap({'name': 'Ben', 'age': 23}, {'name': 'Thinh', 'age': 25})
So how the dictionary search for a provided key? It will search for the key from left to right and return the value once the key is found.
Outcome: Ben
Create a Read-Only DictionaryScenario
As you know, the dictionary allows the users to access and change the items within the dictionary. What if you just want to use the dictionary to provide the users with information about the key without changing it? Like creating a map of classes that could not be changed by students? Then you should consider usingMappingProxyType .
MappingProxyType
MappingProxyType provides a read-only view into the wrapped dictionary’s data. This discourages users from editing the dictionary.
from types import MappingProxyType
#Can read and edit<br>classes = {'Math': 'B23','Physics':'D24'}<br>classes['Math']<br>classes["Math"] = 'B21'
#Can read<br>classes['Math']<br>#But can no longer edit<br>classes["Math"] = "D15"
Outcome:
TypeError: 'mappingproxy' object does not support item assignment
As you can see, now the students can no longer change the room to confuse their classmates.
Conclusion
Congratulation! If you have gone to the end of this article, you know what other dictionary implementations are available and when to use them. Having this knowledge would be useful as you want your dictionary to perform specific functions. So should you switch the standard dictionary with these special dictionary implementations? I advise you to use the standard dictionary and grab these tools as you need a specific function. Even though these dictionary implementations, most of the time, you will find yourself doing just fine with the standard dictionary. Save this article and go back to this as you need to implement the dictionary differently.