Dictionaries

Written by Harnoor Chima (9/11/20)

Introduction

This lesson will cover how to use dictionaries in Python to store values that are assigned to keys. Dictionaries are very useful when you are trying to store a large amount of data in an organized manner.

Format

This format of a dictionary is fairly simple, you give it a name like a normal variable and then you open curly brackets where you will put keys and their corresponding values separated by a colon.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

print(pet)

output: {"name": "fido", "animal": "dog", "age": 2}

Accessing a Dictionary

To access individual values of specific keys inside a dictionary you write the name of the key in square brackets. We can use it in this example to find out what type of animal our pet is.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

x = pet["animal"]
print(x)

output: "dog"

Changing Values

We can also change the values that are assigned to a specific key. So in this example we can say that the pet has aged by 3 years so we change the value for age accordingly.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

pet["age"] = 5

print(pet["age"])

output: 5

Adding/Removing Items

We can also change a dictionary to include another key and value after it has already been created.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

pet["breed"] = "beagle"

If we want to remove a key and value, we can do that by using the pop() method and specifying the key name that we want to get rid of.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

pet.pop("animal")

Looping Through a Dictionary

We can loop through a dictionary by using a for loop to return the keys of a dictionary.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

for x in pet:
    print(x)
    
output: 
name
animal
age

If we want to get all of the values from a dictionary we have to slightly modify our loop.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

for x in pet:
    print(pet[x])

#Alternatively
for x in pet.values():
    print(x)

output: 
fido
dog
2

And finally, you can use the items() method to loop through both the keys and the values.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

for x, y in pet.items():
    print(x, y)

output: 
name fido
animal dog
age 2

Checking if a Key Exists in a Dictionary

We can use a simple if statement to find out if a specific key is contained within a dictionary.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

if "animal" in pet:
    print("'animal' is a key in the pet dictionary")

Copying a Dictionary

Dictionaries can not simply be assigned to another variable, ex: dict1 = dict2, because any changes made to dict1 will also be made to dict 2. This is why, when we want to copy a dictionary we have to use the copy() method.

pet = {
    "name": "fido",
    "animal": "dog",
    "age": 2 
}

pet_copy = pet.copy()
print(pet_copy)

output:
pet = {"name": "fido", "animal": "dog", "age": 2}

Nested Dictionaries

We can use the concept of nested dictionaries to store many dictionaries inside of a single dictionary. This can be useful when we want to have multiple keys in our dictionary with multiple values.

pets = {
    "pet1" : {
        "name" : "Fido",
        "animal" : "dog",
        "age": 2
    },
    "pet2" : {
        "name" : "Ray",
        "animal" : "cat",
        "age": 3
    }, 
    "pet3" : {
        "name" : "Jack",
        "animal" : "dog",
        "age": 5
    } 
} 

Dictionary Constructor

We can use a function called dict() to construct a dictionary for use using preset variables.

pet = dict(name = "Fido", animal = "dog", age = "2")
print(pet)

output: {"age": 2, "animal": "dog", "name": "Fido"}

Conclusion

In this lesson, we learned how to use dictionaries to be able to store many values for just one key item. This will allow us to have more detailed indexes of a specific item. We also learned how to manipulate dictionaries by accessing or changing the contents within them.

Last updated