πŸ“ Dictionaries#

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered and changeable. Dictionaries do not allow duplicates.

Dictionaries are written with curly brackets, and have keys that correspond to values:

thisdict = {
    "Student": "Jay",
    "University": "Drexel",
    "College": "Engineering",
    "class": 2024,
}

print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'class': 2024}

Dictionary Items#

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs and can be referred to by using the key name.

thisdict = {
    "Student": "Jay",
    "University": "Drexel",
    "College": "Engineering",
    "class": 2024,
}

print(thisdict["class"])
2024

Ordered Dictionary#

The meaning of β€œordered” is that the items in a dictionary have a defined order, and that order will not change.

This allows you to iterate through a dictionary in a set order. This concept will become important especially when using loops.

Changeable#

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

thisdict["class"] = 2025

print(thisdict["class"])
2025
thisdict["major"] = "Undeclared Engineering"

print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'class': 2025, 'major': 'Undeclared Engineering'}

Duplicates are Not Allowed#

Dictionary keys must be unique. Dictionaries cannot have two items with the same key:

thisdict = {
    "Student": "Jay",
    "University": "Drexel",
    "College": "Engineering",
    "class": 2024,
    "class": "Engr131",
}

print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'class': 'Engr131'}

If code is written in this way, the dictionary will have the last entry to the key after the code is executed.

Dictionary Length#

print(len(thisdict))
4

Dictionary Item Types#

Items in dictionaries can be of any type

thisdict = {
    "Student": "Jay",
    "University": "Drexel",
    "College": "Engineering",
    "class": 2024,
    "colors": ["blue", "gold"],
    "graduated": False,
}

print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'class': 2024, 'colors': ['blue', 'gold'], 'graduated': False}

Type of a Dictionary#

Python dictionaries are viewed as the type dictionary.

print(type(thisdict))
<class 'dict'>

Dictionary Constructor#

A dictionary is defined or built with code such as the following.

thisdict = dict(
    Student="Jay",
    University="Drexel",
    College="Engineering",
    Class=2024,
    colors=["blue", "gold"],
    graduated=False,
)
print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'Class': 2024, 'colors': ['blue', 'gold'], 'graduated': False}

Accessing Items From Dictionary#

Getting a Value#

The value associated with the key is accessed by putting the key in [] immediately following the dictionary name.

print(thisdict["Class"])
2024
x = thisdict.get("Class")

print(x)
2024

Getting Keys#

Returns all the keys in a dictionary. The keys are returned in order.

x = thisdict.keys()

print(x)
dict_keys(['Student', 'University', 'College', 'Class', 'colors', 'graduated'])

Get Values#

Returns all of the values in a dictionary. The values are returned in order

x = thisdict.values()

print(x)
dict_values(['Jay', 'Drexel', 'Engineering', 2024, ['blue', 'gold'], False])

Get Items#

This returns the key:value pairs. The results are returned in order.

x = thisdict.items()

print(x)
dict_items([('Student', 'Jay'), ('University', 'Drexel'), ('College', 'Engineering'), ('Class', 2024), ('colors', ['blue', 'gold']), ('graduated', False)])

Modifying a Dictionary#

Updating Values#

By Assignment#

print(thisdict["Class"])

thisdict["Class"] = 2025

print(thisdict["Class"])
2024
2025

Using the Update Method#

thisdict.update({"Class": 2024})

print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'Class': 2024, 'colors': ['blue', 'gold'], 'graduated': False}

Removing Items#

Removing by key value

thisdict = dict(
    Student="Jay",
    University="Drexel",
    College="Engineering",
    Class=2024,
    colors=["blue", "gold"],
    graduated=False,
)

thisdict.pop("Class")

print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'colors': ['blue', 'gold'], 'graduated': False}

Removing the last item

thisdict.popitem()
print(thisdict)
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'colors': ['blue', 'gold']}

Copying a Dictionary#

You might think that you can copy a dictionary using assignment.

thisdict_copy = thisdict

Actually, when you assign a dictionary to a new variable, it will occupy the same spot in memory.

thisdict_copy is thisdict
True
# This will clear the dictionary
thisdict_copy.clear()

print(thisdict)
{}

The original dictionary has been deleted.

.copy() method#

This method makes a copy in a different location in memory. It is necessary to make a copy in a different location in memory in order to modify each copy independently.

thisdict = dict(
    Student="Jay",
    University="Drexel",
    College="Engineering",
    Class=2024,
    colors=["blue", "gold"],
    graduated=False,
)

thisdict_copy = thisdict.copy()
thisdict_copy is thisdict
False

The objects are not the same.

thisdict_copy == thisdict
True

The values are the same.

.clear() method#

This method removes the key:value pairs from the dictionary to which it is applied.

# This will clear the dictionary
thisdict_copy.clear()

print("thisdict_copy is now cleared:")
print(thisdict_copy)

print("thisdict was unchanged:")
print(thisdict)
thisdict_copy is now cleared:
{}
thisdict was unchanged:
{'Student': 'Jay', 'University': 'Drexel', 'College': 'Engineering', 'Class': 2024, 'colors': ['blue', 'gold'], 'graduated': False}

Nested Dictionaries#

Using a single dictionary constructor, one can have nested dictionaries in one dictionary.

mystudents = {
    "Student1": {"name": "Quinn", "year": 2024},
    "Student2": {"name": "River", "year": 2022},
    "Student3": {"name": "Jay", "year": 2023},
}

print(mystudents)
{'Student1': {'name': 'Quinn', 'year': 2024}, 'Student2': {'name': 'River', 'year': 2022}, 'Student3': {'name': 'Jay', 'year': 2023}}

Alternatively, if those dictionaries are separately assigned, they can then be combined.

student1 = {"Student": {"name": "Quinn", "year": 2024}}

student2 = {"Student": {"name": "River", "year": 2022}}

student3 = {"Student": {"name": "Jay", "year": 2023}}

mystudents = {"Student1": student1, "Student2": student2, "Student3": student3}

print(mystudents)
{'Student1': {'Student': {'name': 'Quinn', 'year': 2024}}, 'Student2': {'Student': {'name': 'River', 'year': 2022}}, 'Student3': {'Student': {'name': 'Jay', 'year': 2023}}}