Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons


LoginGet Started
← Back to Lessons
Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge
Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
Edit on Github

What are Python Dictionaries?

Exploring Python Dictionaries

Exploring Python Dictionaries

Dictionaries in Python are a data structure that allows us to store large amounts of data and access them in a very efficient way. In this article you will learn how to create, access and modify data in a Python dictionary, in the following example we will see a small demonstration of how you can use a dictionary to store a collection of data.

1city = { 2 #Key Value 3 "city_id": 1, 4 "city_name": "New York", 5 "population": 8,468, 6 "currency": " dollar" 7} 8 9city["city_id"] = 1000 # Replace data within the dictionary. 10city["city_name"] = city["city_name"].upper() # Modify data inside the dictionary 11del city["currency"] # Delete data within the dictionary 12 13print(city)

output city:

1{ 2 'city_id': 1000, 3 'city_name': 'NEW YORK', 4 'population': 8,468 5}

In this example, we create a dictionary with data to represent a city, in the example we access the property city_id and replace its original value 50 with a new value 1000, we modify the property city_name with the same value but in capital letters NEW YORK and finally we eliminate the property currency of the dictionary. In this code, we can see the most basic examples of how to access a property, how to modify data, and how to delete properties in the dictionary.

What is a Python dictionary?

A Python dictionary is a data structure where you can store information in an organized way. Think of it as a real dictionary, but instead of finding definitions of words, you will have values associated with unique keys! Each element of the dictionary is a key-value pair, where the key is unique and allows us to access its corresponding value. This way we can quickly find what we need.

The following video shows better how dictionaries work in Python, how to access their properties, how to update their values, and many more.

How to declare a dictionary?

To declare a dictionary in Python you can do it in two ways, the first one is to create a variable and assign it as value a pair of braces {} this will create a dictionary by default, another way to declare a dictionary is to create a variable and assign it as value the dict() constructor, in the following examples you will see a little better how it works.

1object_one = { 2 "key_one": "object one value one", 3 "key_two": "object one value two", 4} 5 6object_two = dict( 7 key_one = "object two value one", 8 key_two = "object two value two", 9) 10 11print(object_one) 12print(object_two)

output:

1{ 2 'key_one': 'object one value one', 3 'key_two': 'object one value two' 4} 5{ 6 'key_one': 'object two value one', 7 'key_two': 'object two value two' 8}

As you can see, creating a dictionary in Python is very simple, first you create a variable and assign it a pair of keys {}, then inside the keys we create a key and to this key we assign a value, for example: { "academy": "4Geeks" }.

Although it is possible to declare a dictionary with the dict() constructor, I recommend that you use the {} braces as it is considered good practice and makes the code easier to read.

Accessing the data!

To access the data inside a dictionary use the syntax dictionary_name[key], or you can also use the get() method with the following syntax dictionary_name.get(key) as shown in the following example:

1person = { 2 "name": "Axel", 3 "age": 32, 4 "email": "axel@mail.com", 5 "phone": "(123) 456-7890" 6} 7 8print(person["name"]) # output: Axel 9print(person["age"]) # output: 32 10 11print(person.get("email")) # output: axel@mail.com 12print(person.get("phone")) # output: (123) 456-7890 13 14print(person["weight"]) # output: Throws an error (KeyError: 'peso') and stops execution because the key (peso) does not exist in the object persona 15print(person.get("weight")) # output: Although the key (weight) does not exist in the object persona the method get() does not stop the execution and returns: None

As shown in this example, to access the value of a dictionary you can use the square brackets and inside the brackets the name of the key of that value variable[key] or you can also use the get() method and pass as parameter the name of the key that contains the value variable.get(key).

It is important to note that if you try to access the key of a dictionary that does not contain that key using the square brackets you will get a KeyError and it will stop the execution of the code while if you use the get() method it does not stop the execution of the code and returns the value None.

Adding new data!

To add a new item to a dictionary there are several ways, you can use the syntax dictionary_name[new key] = new value to add a new item or you can also use the update() method to add several items at once as shown in the following example:

1object_one = { "key_1": 1, "key_2": 2 } 2object_two = { 1: "A", 2: "B", 3: "C" } 3 4object_one["key_3"] = 3 5object_one["key_4"] = 4 6 7object_two.update({ 4: "D", 5: "E" }) 8 9print(object_one) 10print(object_two)

output:

1{ 'key_1': 1, 'key_2': 2, 'key_3': 3, 'key_4': 4} 2 3{ 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E' }

As we see in this example, you can use the {} braces syntax and inside the braces the name of the new key to create a new value inside a dictionary, but if you need to create more than one value you can use the update() method and pass as parameter a dictionary with the new values.

Deleting data!

To remove a key-value from a dictionary, you can use the syntax del dictionary_name[key] or you can also use the pop() method and pass as a parameter the key name of the value you want to remove as shown in the following example:

1person = { 2 "name": "Axel", 3 "age": "32", 4 "email": "axel@mail.com", 5 "phone": "(123) 456-7890", 6 "weight": 80 7} 8 9from person["weight"] 10age = person.pop("age") 11 12print(age) # output: 32 13print(person)

output person:

1{ 2 'name': 'Axel', 3 'email': 'axel@mail.com', 4 'phone': '(123) 456-7890' 5}

As shown in the example, you can use the reserved word del and then access the dictionary key person["weight"] to delete it. Another way in which you can remove a key-value from a dictionary is by using the pop() method, this method receives as a parameter the name of the key, removes that key-value from the dictionary, and returns the value it removed, which in the example is stored in the age variable.

Iterating through a dictionary!

To iterate through a dictionary you can do it in many ways, in the following example we will see a simple case making use of the for loop structure:

1person = { 2 "name": "Axel", 3 "age": 32, 4 "email": "axel@mail.com", 5 "phone": "(123) 456-7890", 6 "weight": 80 7} 8 9for key in person: 10 value = person[key] 11 print(f "Key: '{key}', value: '{value}'")

output:

1Key: 'name', value: 'Axel' 2Key: 'age', value: '32' 3Key: 'email', value: 'axel@mail.com' 4Key: 'phone', value: '(123) 456-7890' 5Key: 'weight', value: '80'

As we can see in this example, iterating a dictionary is very simple, you can do it with a for loop and a few lines of code. In this example, we iterate the dictionary and display in the console the name of the key and the value of that key in each iteration.

Dictionary methods!

In the following video tutorial, you will see some of the most important dictionary methods, and below the video, you will see a table with some more methods.

These are some of the most relevant dictionary methods.

MethodDescription
clear()Deletes all dictionary elements.
copy()Creates a shallow copy of the dictionary.
get()Returns the value associated with a specific key.
items()Returns a view of (key, value) tuples for each key-value pair in the dictionary.
keys()Returns a view of the keys in the dictionary.
values()Returns a view of the values in the dictionary.
pop()Deletes and returns the value associated with a specific key.
popitem()Removes and returns an arbitrary (key, value) pair from the dictionary.
setdefault()Returns the value associated with a specific key. If the key does not exist, a new entry with value is created.
update()Updates the dictionary with key-value pairs from another dictionary or from a sequence of tuples.

Conclusion

In conclusion, dictionaries are an excellent storage structure that allows you to store large amounts of data each with a key and a value, you can use any type of data as a key for a dictionary except for other dictionaries, lists or tuples. I hope you find this article useful to learn more about dictionaries and how to work with them. If you want to learn more about this programming language I invite you to read the following Python tutorial in the 4Geeks Blog.