Dictionaries

Learn specialized container datatypes: defaultdict and OrderedDict.

Introduction

A dictionary is a built-in data structure that holds items as key: value pairs. To index the dictionary, we can’t use a range of numbers. Keys (only immutable types allowed) serves the purpose of indexing. It’s an unordered structure.

The defaultdict container

This container is a subclass of dict. We will only look into its constructor here. The defaultdict([default_factory[, ...]]) constructor is used to create a dictionary. The argument default_factory attribute is used to specify the type of dictionary object to be returned. By default, it’s None. We can specify it, e.g., as list, set or int, etc.

Run the following code to see how a defaultdict works.

Press + to interact
from collections import defaultdict
s = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('b', 1), ('a', 4)]
d = defaultdict(list)
for key, value in s:
d[key].append(value) # Making key value pairs
print(d.items())

In the code above, we import the defaultdict subclass at line 1. Here, we are trying to make a dictionary out of list. So at line 3, we are making a list s. Analyze the format carefully. The list has tuples. We ...