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

Motivation

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
}
food['fish']
  • 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

Scenario

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.

OrderDict

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

Scenario

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.

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'
classes['Math']
classes['English']

Group Multiple Dictionaries into a Single Mapping

Scenario

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

Create a Read-Only Dictionary

Scenario

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

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

Conclusion

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 https://mathdatasimplified.com/

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