Boost Your Efficiency With Specialized Dictionary Implementations in Python

Create dictionaries with ordered and read-only items, return default values for non-existent keys, and much more

Khuyen Tran
Feb 10 · 5 min read
Photo by oxana v on Unsplash


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 it simply, imagine going to a grocery store, if you want to find the price of an item, you just need to input the name of the item and the price associated with the item will be immediately returned.

food = {
'fish': 10,
'broccoli': 3,
'tofu': 5,
'mushroom': 3
  • Returning the default values when there’s no requested key.
  • Grouping multiple dictionaries into a single mapping.
  • Creating a read-only dictionary.

Create an Ordered Dictionary


You want to use a dictionary to organize the tasks that you want to finish for the weekend. The dictionary keys are the tasks, the values are the hours needed 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.


collections.OrderedDict is ideal if key order is important for your goal.

import collectionstasks = collections.OrderedDict(laundry=0.5, shopping=2, clean=2)tasks['movie'] = 2taskstasks.keys
OrderedDict([('laundry', 0.5), ('shopping', 2), ('clean', 2), ('movie', 2)])odict_keys(['laundry', 'shopping', 'clean', 'movie'])

Return the Default Value when There’s no Requested Key


You 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.


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 defaultdictclasses = defaultdict(lambda: 'Outside')classes['Math'] = 'B23'
classes['Physics'] = 'D24'

Group Multiple Dictionaries into a Single Mapping


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.


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 informationfriend1 = {'name':'Ben','age':23}
friend2 = {'name':'Thinh', 'age': 25}
#Group these dictionaries togetherfriends = ChainMap(friend1, friend2)
ChainMap({'name': 'Ben', 'age': 23}, {'name': 'Thinh', 'age': 25})

Create a Read-Only Dictionary


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? For example, creating a map of classes that could not be changed by students. Then you should consider usingMappingProxyType .


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
classes = {'Math': 'B23','Physics':'D24'}
classes["Math"] = 'B21'
#Can read
#But can no longer edit
classes["Math"] = "D15"
TypeError: 'mappingproxy' object does not support item assignment


Congratulations! 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 will be useful as you want your dictionary to perform specific functions.

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Khuyen Tran

Written by

Draw connection between math, data science, and random events to create interesting data science projects

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade