Skip to content

Dictionaries & Hashmaps

Dictionaries or hashmaps are data structures that store key-value pairs. They are implemented using hash tables, which allow for efficient insertion, deletion, and lookup operations.

Import packages

from collections import Counter, defaultdict

Define a dictionary

empty_dict = {}
empty_dict, type(empty_dict)
({}, dict)

Creating a dictionary

empty_dict = dict()
empty_dict
{}

Adding an element to a dictionary - O(1)

empty_dict["name"] = "Gabriel"
empty_dict
{'name': 'Gabriel'}

Defining a dictionary with elements

student = {"name": "John", "age": 20, "grade": "A"}
student
{'name': 'John', 'age': 20, 'grade': 'A'}

Check if an element is in the dictionary - O(1)

"name" in student
True

Accessing dictionary elements - O(1)

student = {"name": "John", "age": 20, "grade": "A"}
student["grade"]
'A'

Accessing dictionary elements

1
2
3
4
student = {"name": "John", "age": 20, "grade": "A"}
print(student.get("grade"))
print(student.get("last_name"))
print(student.get("last_name", "Not available"))
A

None

Not available

Modifying dictionary elements

1
2
3
4
5
6
7
8
student = {"name": "John", "age": 20, "grade": "A"}
print(student)
student["age"] = 21
print(student)
student["last_name"] = "Doe"
print(student)
del student["grade"]
print(student)
{'name': 'John', 'age': 20, 'grade': 'A'}

{'name': 'John', 'age': 21, 'grade': 'A'}

{'name': 'John', 'age': 21, 'grade': 'A', 'last_name': 'Doe'}

{'name': 'John', 'age': 21, 'last_name': 'Doe'}

Retrieving dictionary keys

student = {"name": "John", "age": 20, "grade": "A"}
student.keys()
dict_keys(['name', 'age', 'grade'])

Retrieving dictionary values

student = {"name": "John", "age": 20, "grade": "A"}
student.values()
dict_values(['John', 20, 'A'])

Transforming a dictionary into an list of tuples

student = {"name": "John", "age": 20, "grade": "A"}
student.items()
dict_items([('name', 'John'), ('age', 20), ('grade', 'A')])

Copying a dictionary

1
2
3
4
5
6
student = {"name": "John", "age": 20, "grade": "A"}
student_copy = student
print(student_copy)
student["age"] = 21
print(student_copy)
print(student)
{'name': 'John', 'age': 20, 'grade': 'A'}

{'name': 'John', 'age': 21, 'grade': 'A'}

{'name': 'John', 'age': 21, 'grade': 'A'}

Using a shallow copy of a dictionary

1
2
3
4
5
6
student = {"name": "John", "age": 20, "grade": "A"}
student_shallow_copy = student.copy()
print(student_shallow_copy)
student["age"] = 22
print(student_shallow_copy)
print(student)
{'name': 'John', 'age': 20, 'grade': 'A'}

{'name': 'John', 'age': 20, 'grade': 'A'}

{'name': 'John', 'age': 22, 'grade': 'A'}

Iterating over a dictionary keys - O(n)

1
2
3
student = {"name": "John", "age": 20, "grade": "A"}
for keys in student.keys():
    print(keys)
name

age

grade

Iterating over a dictionary values - O(n)

1
2
3
student = {"name": "John", "age": 20, "grade": "A"}
for keys in student.values():
    print(keys)
John

20

A

Iterating through a dictionary items - O(n)

1
2
3
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
    print(key, value)
name John

age 20

grade A

Dictionary comprehension

squares = {x: x**2 for x in range(1, 6)}
squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Dictionary comprehension

squares = {x: x**2 for x in range(1, 6) if x % 2 == 0}
squares
{2: 4, 4: 16}

Counting occurrences of numbers in a list

1
2
3
numbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4]
number_count = {num: numbers.count(num) for num in set(numbers)}
number_count
{1: 4, 2: 3, 3: 3, 4: 6}

Merging dictionaries

1
2
3
4
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {**dict1, **dict2}
merged_dict
{'a': 1, 'b': 3, 'c': 4}

Default dict

python's collections module provides a defaultdict class that allows you to create dictionaries with default values for missing keys. This can be useful when you want to avoid key errors and provide a default value when a key is not present in the dictionary.

1
2
3
default = defaultdict(int)

default[100]
0

Counter is a subclass of defaultdict that is specifically designed for counting hashable objects. It provides a convenient way to count the occurrences of elements in a collection, such as a list or a string.

O(n) for counting occurrences of numbers in a list using Counter.

1
2
3
4
text = "She sells seashells by the seashore"

counter = Counter(text)
counter
Counter({'e': 7,
         's': 7,
         ' ': 5,
         'h': 4,
         'l': 4,
         'a': 2,
         'S': 1,
         'b': 1,
         'y': 1,
         't': 1,
         'o': 1,
         'r': 1})