Guide to Dictionaries in Python

Introduction

Python comes with a variety of built-in data structures, capable of storing different types of data. A Python dictionary is one such data structure that can store data in the form of key-value pairs - conceptually similar to a map. The values in a Python dictionary can be accessed using the keys.

In this guide, we will be discussing Python dictionaries in detail. Firstly, we'll cover the basic dictionary operations (creating a dictionary, updating it, removing and adding elements, etc.) and take a look at a couple more interesting methods afterward.

How To Create a Dictionary in Python

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma (,). Each entry consists of a key and a value, also known as a key-value pair.

Note: The values can belong to any data type and they can repeat, but the keys must remain unique. Additionally, you can't assign multiple values to the same key, though, you can assign a list of values (as a single value).

Now that we understand what dictionaries are, let's see how to use them in Python. First of all, we need to understand how to create an empty dictionary:

example_dict = {}

Great! We now have an empty directory. But what if we want to both create and fill a dictionary with some initial data? That's also a pretty easy task in Python - say we have integer keys and string values:

example_dict = {1: 'mango', 2: 'pawpaw'}

As we said before, it's not necessary that all keys are of the same type:

example_dict = {'fruit': 'mango', 1: [4, 6, 8]}

Alternatively, we can create a dictionary by explicitly calling the Python's dict() constructor:

example_dict = dict({1:'mango', 2:'pawpaw'})

A dictionary can also be created by passing a list of tuples to the dict() constructor:

example_dict = dict([(1,'mango'), (2,'pawpaw')])

Dictionaries can also be nested, which means that we can create a dictionary inside another dictionary:

example_dict = {1: {'student1' : 'Nicholas', 'student2' : 'John', 'student3' : 'Mercy'},
        2: {'course1' : 'Computer Science', 'course2' : 'Mathematics', 'course3' : 'Accounting'}}

To print the dictionary contents, we can use Python's print() method and pass the dictionary name as the argument to the method:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

print(example_dict)

This results in:

{'Company': 'Toyota', 'model': 'Premio', 'year': 2012}

Note: For concise and readable dictionary creation, consider dictionary comprehensions, especially when deriving from another data source:

squares = {x: x*x for x in range(5)}

How To Access Elements of a Python Dictionary

To access dictionary items - we pass the key, using the square bracket notation:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

x = example_dict["model"]

print(x)

This nets us the value associated with the "model" key:

Premio

You can store "configuration" items or common constants in a dictionary for ease of centralized access:

example_dict = {'Name': 'Mercy', 'Age': 23, 'Course': 'Accounting'}

print("Student Name:", example_dict['Name'])
print("Course:", example_dict['Course'])
print("Age:", example_dict['Age'])

This would yield us with:

Student Name: Mercy
Course: Accounting
Age: 23

The dictionary object also provides the get() method, which can be used to access dictionary elements as well. We append the method with the dictionary name using the dot operator and then pass the name of the key as the argument to the method:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

x = example_dict.get("model")

print(x) # Output: Premio

Now we know how to access dictionary elements! In the next section, we'll discuss how to add new elements to an already-existing dictionary.

Note: Rather than directly accessing a key, which could result in a KeyError, use the get() method to provide a default value.

value = my_dict.get("key", default_value)

How To Add Elements to a Python Dictionary

There are numerous ways to add new elements to a dictionary. A common way is to add a new key and assign a value to it:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

example_dict["Capacity"] = "1800CC"

print(example_dict)

When a key doesn't exist, and we assign a value to it - it gets added to the dictionary:

{'Capacity': '1800CC', 'year': 2012, 'Company': 'Toyota', 'model': 'Premio'}

The new element has Capacity as the key and 1800CC as its corresponding value. It has been added as the first element of the dictionary. Here is another example. First, let's first create an empty dictionary:

example_dict = {}

print("An Empty Dictionary: ")
print(example_dict)

Let's verify that it's empty:

An Empty Dictionary:

The dictionary returns nothing as it has nothing stored yet. Let us add some elements to it, one at a time:

example_dict[0] = 'Apples'
example_dict[2] = 'Mangoes'
example_dict[3] = 20

print("3 elements have been added: ")
print(example_dict)

This results in:

3 elements have been added:
{0: 'Apples', 2: 'Mangoes', 3: 20}

Note: Starting from Python 3.7, dictionaries maintain the order of items based on their insertion. This behavior is guaranteed in Python 3.8+.

To add the elements, we specified keys as well as the corresponding values:

example_dict[0] = 'Apples'

In the above example, 0 is the key while Apples is the value. It is even possible for us to add a set of values to one key as long as that set is referenceable as a single value, such as a collection:

# These three values are implicitly converted into a set
example_dict['Values'] = 1, "Pairs", 4

print("3 elements have been added: ")
print(example_dict)

And we have a key with a set as its value:

3 elements have been added:
{'Values': (1, 'Pairs', 4)}

Other than adding new elements to a dictionary, dictionary elements can also be updated/changed, which we'll go over in the next section.

Advice: Read more about adding new keys to a dictionary in Python in our article "Python: How to Add Keys to a Dictionary".

How To Update Dictionary Elements

After adding a value to a dictionary we can then modify the existing dictionary element. You use the key of the element to change the corresponding value:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

example_dict["year"] = 2014

print(example_dict)

In this example, we've updated the value for the key year from the old value of 2012 to a new value of 2014:

{'year': 2014, 'model': 'Premio', 'Company': 'Toyota'}

How To Remove Dictionary Elements

The removal of an element from a dictionary can be done in several ways, which we'll discuss one by one in this section.

The del keyword can be used to remove the element with the specified key. We need to call the del keyword followed by the dictionary name. Inside the square brackets that follow the dictionary name, we passed the key of the element we need to delete from the dictionary, let it be the year:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

del example_dict["year"]

print(example_dict)

This will remove the entry for the year:

{'Company': 'Toyota', 'model': 'Premio'}

Another way to delete a key-value pair is to use the pop() method and pass the key of the entry to be deleted as the argument to the method:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

example_dict.pop("year")

print(example_dict)

We invoked the pop() method by appending it with the dictionary name. Running this code will delete the entry for a year in the dictionary:

{'Company': 'Toyota', 'model': 'Premio'}

If you don't specify the key, the popitem() method removes the last item inserted into the dictionary:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

example_dict.popitem()

print(example_dict)

The last entry into the dictionary was the year. It has been removed after calling the popitem() method:

{'Company': 'Toyota', 'model': 'Premio'}

But what if you want to delete the entire dictionary? It would be difficult and cumbersome to use one of these methods on every single key. Instead, you can use the del keyword to delete the entire dictionary:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

del example_dict

print(example_dict)

But, this code will return an error. The reason is that we are trying to access a dictionary that doesn't exist since it has been deleted beforehand:

NameError: name 'example_dict' is not defined

Depending on the use case, you might need to remove all dictionary elements but not the dictionary itself. This can be achieved by calling the clear() method on the dictionary:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

example_dict.clear()

print(example_dict)

This will give you an empty dictionary (since all the dictionary elements have been removed):

{}

Other Common Dictionary Methods in Python

Besides methods we've covered so far, Python provides us with a lot of other interesting methods that help us perform operations other than the basic ones described before. In the following subsections, we'll take a look at some other methods you can use alongside dictionaries in Python.

Note: Remember that methods like keys(), values(), and items() return view objects, which are dynamic in nature. This means if the dictionary changes, these views will reflect the change.

len() Method

With this method, you can count the number of elements in a dictionary:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

print(len(example_dict))

There are three entries in the dictionary, hence the method will return 3:

3

Advice: Read more about calculating the size of dictionaries in Python in our article "Python: Get Size of Dictionary".

copy() Method

This method returns a copy of the existing dictionary:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}
x = example_dict.copy()

print(x)

Let's make sure the copy is properly made and assigned to the variable x:

{'Company': 'Toyota', 'year': 2012, 'model': 'Premio'}

After printing x in the console, you see that it contains the same elements as those stored in the example_dict dictionary.

Note: This is useful because modifications made to the copied dictionary won't affect the original one.

items() Method

When called, this method returns an iterable object. The iterable object has key-value pairs for the dictionary, as tuples in a list. This method is primarily used when you want to iterate through a dictionary.

The method is simply called on the dictionary object name:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

for k, v in example_dict.items():
  print(k, v)

This will result in:

('Company', 'Toyota')
('model', 'Premio')
('year', 2012)

The object returned by items() can also be used to show the changes that have been implemented in the dictionary:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

x = example_dict.items()

print(x)

example_dict["model"] = "Mark X"

print(x)

This code illustrates that when you change a value in the dictionary, the items object is also updated to reflect this change:

dict_items([('Company', 'Toyota'), ('model', 'Premio'), ('year', 2012)])
dict_items([('Company', 'Toyota'), ('model', 'Mark X'), ('year', 2012)])

keys() Method

This method also returns an iterable object. The object returned is a list of all keys in the dictionary. And just like with the items() method, the returned object can be used to reflect the changes made to the dictionary.

To use this method, we only call it on the name of the dictionary:

dictionary.keys()

For example:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

x = example_dict.keys()

print(x)

This will give us:

dict_keys(['model', 'Company', 'year'])

Often times this method is used to iterate through each key in your dictionary:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

for k in example_dict.keys():
  print(k)

This will print each key of the example_dict in a separate line:

Company
model
year

fromkeys() Method

This method returns a dictionary having specified keys and values:

dictionary.fromkeys(keys, value)

The value for the required keys parameter is iterable and it specifies the keys for the new dictionary. The value for the value parameter is optional and it specifies the default value for all the keys. The default value for this is None.

Suppose we need to create a dictionary of three keys all with the same value, say 25:

name = ('John', 'Nicholas', 'Mercy')
age = 25

example_dict = dict.fromkeys(name, age)

print(example_dict)

Let's verify that the fromkeys() method created the dictionary we've described:

{'John': 25, 'Mercy': 25, 'Nicholas': 25}

As expected, the fromkeys() method was able to pick the keys and combine them with the value 25 to create the dictionary we wanted.

The value for the keys parameter is mandatory. The following example demonstrates what happens when the value for the values parameter is not specified:

name = ('John', 'Nicholas', 'Mercy')

example_dict = dict.fromkeys(name)

print(example_dict)

In this case, None was used as the default value:

{'John': None, 'Mercy': None, 'Nicholas': None}

setdefault() Method

This method is applicable when we need to get the value of the element with the specified key. If the key is not found, it will be inserted into the dictionary alongside the specified default value.

The method takes the following syntax:

dictionary.setdefault(keyname, value)

In this method, the keyname parameter is required. It represents the key name of the item you need to return a value from. The value parameter is optional. If the dictionary already has the key, this parameter won't have any effect. If the key doesn't exist, then the value given in this method will become the value of the key. It has a default value of None:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

x = example_dict.setdefault("color", "Gray")

print(x)

The dictionary doesn't have the key for color. The setdefault() method has inserted this key and the specified value, that is, Gray, has been used as its value:

Gray

The following example demonstrates how the method behaves if the value for the key does exist:

example_dict = {
  "Company": "Toyota",
  "model": "Premio",
  "year": 2012
}

x = example_dict.setdefault("model", "Allion")

print(x)

The value Allion has no effect on the dictionary since we already have a value for the key model:

Premio

Dictionary Comprehensions

Dictionary comprehensions, akin to list and set comprehensions, offer a concise way to create dictionaries. Common applications include constructing dictionaries from iterables, transforming existing dictionaries, or filtering dictionary content. This section will guide you through the mechanics and potential uses of dictionary comprehension.

Advice: You can take a deeper dive into the topic of dictionary comprehensions in Python by reading our "Python Dictionary Comprehension: A Fast and Flexible Way to Build Dictionaries" article.

The basic syntax of a dictionary comprehension is pretty similar to the one used for the list comprehension:

{key_expr: value_expr for item in iterable}

The key_expr and value_expr are expressions defining the key-value pairs based on the current item in the iterable.

To illustrate this, let's construct a dictionary that maps numbers to their squares:

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

Sometimes, you'd like to filter out certain values when creating a dictionary. For that purpose, you can introduce conditions in the dictionary comprehension syntax:

even_squares = {x: x*x for x in range(6) if x % 2 == 0}
print(even_squares)  # Output: {0: 0, 2: 4, 4: 16}

Dictionary comprehension in Python is a powerful mechanism enabling us to do much more than just create simple dictionaries. For example, you can also use it to create and access nested dictionaries:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = {j: {i: matrix[i][j] for i in range(3)} for j in range(3)}
print(transpose)  # Output: {0: {0: 1, 1: 4, 2: 7}, 1: {0: 2, 1: 5, 2: 8}, 2: {0: 3, 1: 6, 2: 9}}

Combining the zip() function with dictionary comprehension can help you create a dictionary from two lists - one containing keys and one containing values of the newly created dictionary:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
result = {k: v for k, v in zip(keys, values)}
print(result)  # Output: {'a': 1, 'b': 2, 'c': 3}

The last usage of dictionary comprehension we'll cover in this article is _modifying an existing dictionary. Let's say you want to create a new dictionary from an existing one, where each value is incremented by 1:

original = {'a': 1, 'b': 2, 'c': 3}
incremented = {k: v + 1 for k, v in original.items()}
print(incremented)  # Output: {'a': 2, 'b': 3, 'c': 4}

Iterating Through Dictionaries

Iteration is a fundamental operation in programming, and when it comes to dictionaries, Python provides several intuitive methods to traverse through keys, values, or both. Let’s explore the different techniques and scenarios for iterating over dictionaries.

Advice: Read more about iterating through dictionaries in Python in our article "How to Iterate Over a Dictionary in Python" .

Iterating Over Keys (Default Behavior)

When you loop through a dictionary directly using a for loop, it iterates over its keys by default:

person = {'name': 'John', 'age': 30, 'city': 'New York'}

for key in person:
    print(key)

This will result in:

name
age
city

We can achieve the same behavior (but more explicitly) by using the keys()method:

for key in person.keys():
    print(key)

Avoid modifying the size of a dictionary while iterating over it. If you need to remove items, consider iterating over a copy of the dictionary's keys:

for key in list(my_dict.keys()):
    if some_condition(key):
        del my_dict[key]

Iterating Over Values Using values()

We'll use the values() method to help us loop through all the values in a dictionary:

for value in person.values():
    print(value)

Output:

John
30
New York

Iterating Over Key-Value Pairs Using items()

This method returns both the key and its corresponding value, which can be unpacked directly within the loop:

for key, value in person.items():
    print(f"{key}: {value}")

This will give us::

name: John
age: 30
city: New York

Nested Dictionaries Iteration

If you have dictionaries within dictionaries, you'll need nested loops to traverse them:

people = {
    'john': {'age': 30, 'city': 'New York'},
    'marie': {'age': 22, 'city': 'Boston'}
}

for name, info in people.items():
    print(f"{name.title()}:")
    for key in info:
        print(f"  {key.capitalize()}: {info[key]}")

We'll get a nicely formatted output:

John:
  Age: 30
  City: New York
Marie:
  Age: 22
  City: Boston

Conditional Iteration

You can also integrate conditions within loops for specific requirements:

# Print only the keys where the value is a string
for key, value in person.items():
    if isinstance(value, str):
        print(key)

Since the value of the age key is an integer, it won't be printed out:

name
city

Dictionary and Memory

Dictionaries, while highly versatile and efficient, can also be memory-intensive due to their underlying data structures and mechanisms. This section aims to explore the memory implications of using dictionaries in Python, providing insights and best practices to ensure optimized memory usage.

Advice: In cases where you don't require the functionality of a full dictionary, consider using a list of tuples or a namedtuple.

There are several causes because dictionaries can be memory-intensive. First of all, dictionaries are essentially implemented using hash tables as their under-the-hood. This ensures O(1) average complexity for lookups but requires extra memory to store hashes, table indices, and handle collisions. Other than that, Python dictionaries are designed to resize when they reach a certain load factor. This means that memory might be allocated in advance, even if not immediately used.

If you're interested in checking the memory usage of a dictionary, you can do so by using Python’s sys module:

import sys
person = {'name': 'John', 'age': 30, 'city': 'New York'}
print(sys.getsizeof(person))  # Returns size in bytes

But what can you do about the size of your dictionaries? Let's take a look at a couple of tips that can help you do a better job of managing your dictionary's size. First of all, if a dictionary grows large and then shrinks (after deletions), it might still retain a large allocated size. In that case, use dict.copy() to create a smaller copy. Additionally, for dictionaries with the same set of keys (like objects of a class), key sharing can save memory. This technique involves using a single memory block to store the keys for multiple dictionaries.

Being conscious of memory implications doesn’t mean you should shy away from dictionaries. Instead, with an informed approach, you can make the most of what dictionaries offer without compromising on system performance.

Conclusion

This marks the end of this guide on Python dictionaries. These dictionaries store data in key-value pairs. The key acts as the identifier for the item while the value is the value of the item. The Python dictionary comes with a variety of methods that can be applied for the retrieval or manipulation of data. In this article, we saw how a Python dictionary can be created, modified, and deleted along with some of the most commonly used dictionary methods.

Last Updated: August 31st, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Nicholas SamuelAuthor

I am a programmer by profession. I am highly interested in Python, Java, Data Science and Machine learning. If you need help in any of these, don't hesitate to contact me.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms