Structures Dictionary

Module 2: Data Structures

Review previous sessions here!


Data Structures: Dictionaries

Dictionaries are the last the built-in data type that we will learn in Python. They are used to store collections of data in key-value pairs.

In a dictionary, a key is a unique identifier pointing to its associated value. While keys must be unique and immutable, values can be of any data type and may be duplicated.

A dictionary is created using curly brackets {}. Here’s an example:

dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

print(dictionary)

We access data inside a dictionary using its keys. Every key returns its associated value.

dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

print(dictionary["key1"])

Keys must be strings or numbers. Values can be anything.

very_complex_dictionary = {
    "number": 3.14,
    "string": "Hello",
    "boolean": True,
    "list": [1, 2, 3, 4],
    "tuple": (1, 2, 3, 4),
    "set": {1, 2, 3, 4},
    "dictionary": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    },
    "function": lambda x: x + 1,
    10: "ten"
}

print(very_complex_dictionary)

We can use other Python variables to define keys or values.

name_value = "John"
key_years = "age"

person = {
    "name": name_value,
    key_years: 25,
    "city": "New York"
}

print(person)

Unordered

Dictionaries are unordered. You cannot use numeric indices to acces an item.

print(person[0])  # This will cause an error!

Instead, you refer to its key:

print(person["name"])  # Outputs: John

However, dictionary keys can be numeric.

numbers = {
    3: "three",
    4: "four",
    5: "five"
}

print(numbers[3])  # Outputs: three
numbers = {
    3: "three",
    4: "four",
    5: "five"
}

print(numbers[2])  # Error: 2 is not a key in that dictionary!

Mutable

Dictionaries are mutable. This means that you can change the value of a specific item by referring to its key:

person = {
    "name": "John",
    "age": 25,
    "city": "New York"
}

print("Dictionary before:")
print(person)

person["age"] = 100

print("Dictionary after:")
print(person)

However, once an item is defined we cannot change its key name, only its associated value.

We can remove keys with del.

person = {
    "name": "John",
    "age": 25,
    "city": "New York"
}

print("Dictionary before:")
print(person)

del person["city"]

print("Dictionary after:")
print(person)

We can initialize empty dictionaries using the curly brackets:

my_dict = {}

print("Empty dictionary:")
print(my_dict)
print(f"Type: {type(my_dict)}")

# Add a new key to it
my_dict["pi"] = 3.1415

print("Dictionary after:")
print(my_dict)

Wait! Aren’t curly brackets used for sets too? How can we initialize an empty set?

# Initialize an empty set
my_set = set()

print("Empty set:")
print(my_set)
print(f"Type: {type(my_set)}")

No Duplication

Dictionaries do not allow duplicate keys! If we use the same key twice, only the last key will remain.

person = {
    "name": "John",
    "name": "Smith",
    "age": 25,
    "city": "New York"
}

print(person)

However we can have duplicate values:

person = {
    "name": "John",
    "age": 25,
    "city": "John"
}

print(person)

Convert between Structures

You can use the dict function to convert list of tuples into dictionaries.

dict([("person", "Pipo"), ("Age", 10)])

Summary

Data Structure Ordered Mutable Duplication Indexable
List
Tuple
Set
Dictionary

Ready for a Challenge?

Try to beat one of these exercises!

Challenge 1: Create a recommendation system that suggests products to new clients based on their purchases and the purchase history of existing clients.

Challenge 2: Given a list of cities and the distances between each pair of cities, find the shortest possible route that visits each city exactly once and returns to the original city.

Challenge 3: Juan Parrondo stated this paradox within game theory where two games, both of which are losing when played individually, can lead to a winning strategy when played alternately.

Challenge 4: Sudoku is a classic logic-based number-placement puzzle. The objective is to fill a 9x9 grid with digits in such a way that each column, each row, and each of the nine 3x3 sub-grids that compose the grid contains all of the digits from 1 to 9.