Python Dictionary — A Complete Guide

Python dictionary
Image design by Elias Ervast

Python dictionary is an unordered collection of items. Each item is a key-value pair.

Dictionaries can be used to represent labeled data.

For example, you can represent a student as a dictionary:

With dictionaries, it is easy to access, modify, and delete entries.

For example:

In this guide, you learn everything about dictionaries in Python.

How to Define a Python Dictionary

A Python dictionary is a mapping from a key to its associated value. A dictionary is known as an associative array because of this.

There are many ways you can create a dictionary in Python:

  1. Add comma-separated key-value pairs inside of curly braces.
  2. Convert a list of tuples to a dictionary.
  3. Define a dictionary using keyword arguments.
  4. Create a dictionary incrementally.

1. Comma-Separated Key-Value Pairs

This is the most basic way to create a dictionary in Python—Add keys and associated values inside of a set of curly braces. Each key should be followed by a colon that separates it from the value.

Also, don’t forget to add commas between these key-value pairs.

Here is how it looks like. For example, let’s create a student dictionary:

2. Convert a List of Tuples to a Dictionary Using the dict() Function

You can also define the above dictionary this way:

The pairs, such as (“name”, “Alice”) are known as tuples. The built-in dict() function knows that it should convert these to key-value pairs, such as “name”: “Alice”.

3. Define a Dictionary Using Keyword Arguments

If the dictionary keys are strings, you can use the dict() function to create a new dictionary this way:

4. Create a Dictionary Incrementally

The previous examples assume you know what you want to put into the dictionary right away.

But if this is not the case you can create a dictionary incrementally. This means you can define an empty dictionary and add entries to it on the fly.

For example, let’s build the student dictionary incrementally:

How to See the Contents of a Python Dictionary

You just learned four ways to create a dictionary in Python.

Now that you have your first dictionary created, you may want to see that it really contains the elements you want.

To do this, you can print the dictionary similar to how you’d print a list.

Given the student dictionary, here is how to see its contents:

print(student)

Output:

{'name': 'Alice', 'graduated': False, 'married': False, 'age': 23, 'hobbies': ['Jogging', 'Gym', 'Boxing']}

It works!

You may be bothered by the fact that there are no line breaks in the output. At the end of this guide, you will learn how to pretty-print a Python dictionary.

How to Access Python Dictionary Values

Python list elements are accessed via the index using square brackets. For example names[0].

Unlike lists, dictionaries are accessed with the key. Similar to accessing list elements, a dictionary key name is passed into a set of square brackets ([]).

Let’s continue with the student dictionary from the previous chapter

To access the name of the student, you can call:

student["name"]

Let’s print this to see it really works:

print(student["name"])

Output:

Alice

If you try to access a non-existent element in the dictionary, an exception is raised:

student["haircolor"]

Output:

KeyError: 'haircolor'

How to Add a New Key-Value Pair Into a Dictionary

To add a new entry to a dictionary, you need to “access” it with square brackets and assign a value to it.

For example, let’s add the haircolor as a new entry into the student dictionary:

student["haircolor"] = "Red"

Now you can verify that this addition really took place by printing the haircolor of the student:

print(student["haircolor"])

Output:

Red

How to Update a Key-Value Pair In a Dictionary

If you want to update an existing entry in a dictionary, access the entry using the square brackets. Then assign a value to it.

For example, let’s change the age of the student from 23 to 24:

student["age"] = 24

How to Delete a Key-Value Pair From a Dictionary

To delete an entry from a dictionary, use the del statement.

For example, let’s get rid of that haircolor:

del student["haircolor"]

Now you can verify that the changes we made took place by printing out the dictionary:

print(student)

Output:

{'name': 'Alice', 'graduated': False, 'married': False, 'age': 23, 'hobbies': ['Jogging', 'Gym', 'Boxing']}

The haircolor is gone.

Valid Python Dictionary Key Types

So far you have only used a string as a key to the dictionary.

Using strings as keys is a very common way to deal with dictionaries. But it is worthwhile to know you can use other types as keys too.

The dictionary keys can be almost any type. For example:

  • String
  • Integer
  • Float
  • Boolean
  • Tuple
  • Function
  • Object

Also, you can have dictionaries with mixed types. In other words, you can have keys of any type in the same dictionary.

Let’s see a (stupid) example:

Creating entries this way is usually meaningless. But hey at least you now know it works.

Restrictions on Dictionary Keys

Previously you saw you can use almost anything as a dictionary key in Python.

But there are two main restrictions when it comes to dictionary keys.

  1. No duplicate keys. A dictionary is a key-value mapping. Having duplicate keys would be a contradiction. Think about a student having two names…
  2. A dictionary key must be immutable. This makes it possible to use a for example a tuple as a dictionary key. But a list or another dictionary cannot be used as a key. If you are wondering what makes integers, strings, or other types immutable, read this article.

Restrictions on Dictionary Values

There are no restrictions to dictionary values. Not a single one.

You can have duplicate values, immutable and mutable values, and so on.

For instance, you can have a new dictionary as a value:

Dictionary Operators

Next, you are going to learn useful operations you can perform on dictionaries.

Let’s continue with the student dictionary from earlier sections:

In Statement

To check if a specific key exists in a dictionary, use the in statement.

For example, let’s check if a student has a key age:

print("age" in student)

Output:

True

This can be useful. As you may remember, if you try to access a non-existent key, an error is thrown. If you don’t handle this error properly, your program crashes.

This is where you can use the in statement to check if a key exists before accessing the value.

For example:

if "haircolor" in student:
print(f"Hair color is {student['haircolor']}")
else:
print("Haircolor is not defined")

Len() Function

To check the length of a dictionary, use the built-in len() method.

For example, the student dictionary contains five entries. But if you want to check this without calculating the entries yourself, use the len() function:

print(len(student))

Output:

5

Python Dictionary Methods

Python dictionary has a bunch of useful built-in methods. These can help you save time when working with dictionaries.

These methods are:

  • dict.clear()
  • dict.copy()
  • dict.fromkeys()
  • dict.get()
  • dict.items()
  • dict.keys()
  • dict.pop()
  • dict.popitem()
  • dict.setdefault()
  • dict.update()
  • dict.values()

Let’s go through each method in more detail with an example.

dict.clear()

This method wipes out the whole dictionary:

data = {"example 1": 1, "example 2": 10, "Example 3": 100}
data.clear()print(data)

Output:

{}

dict.copy()

Use copy() method to create a copy of the dictionary.

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
data = player_data.copy()print(data)

Output:

{"Ronaldo": 7, "Messi": 10, "Bale": 9}

dict.fromkeys()

Use the fromkeys() method to create a dictionary from a list of keys that all have the same value.

For instance, let’s initialize the weekly precipitation dictionary such that the daily precipitation starts from 0.0 for each day of the week:

weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
precipitation = dict.fromkeys(weekdays, 0.0)print(precipitation)

Output:

{'Sat': 0.0, 'Sun': 0.0, 'Thu': 0.0, 'Wed': 0.0, 'Tue': 0.0, 'Mon': 0.0, 'Fri': 0.0}

dict.get()

To get a value corresponding to a key, you can use the get() method:

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
ronaldo_number = player_data.get("Ronaldo")print(ronaldo_number)

Output:

7

In case you are trying to get a value that does not exist, the get() method returns None by default:

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
non_existent = player_data.get("xyz")print(non_existent)

Output:

None

Sometimes you may want to change this default value to something else than None such as False. You can do this by giving the optional second parameter to the get() method:

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
non_existent = player_data.get("xyz", False)print(non_existent)

Output:

False

dict.items()

The items() method returns a view object, that is, the keys and values as a list of tuples inside a view object.

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
player_items = player_data.items()print(player_items)

If you don’t enjoy the view object, you can convert it to a list with the list() method. Just replace print(player_items) with print(list(player_items)).

dict.keys()

The keys() method returns all the dictionary keys as a list inside a view object. For example:

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
player_keys = player_data.keys()print(player_keys)

Output:

dict_keys(['Messi', 'Bale', 'Ronaldo'])

You can convert this view object into a list with the list() method by replacing print(player_keys) with print(list(player_keys)).

dict.pop()

Use pop() method to remove an element with a specific key.

For instance:

Output:

7
{'Messi': 10, 'Bale': 9}

dict.popitem()

Use popitem() to remove the item that was last inserted into the dictionary. In earlier versions than Python 3.7, the popitem() method removes a random item. The popitem() method returns the removed element as a tuple.

For example:

Output:

Bale
9
{'Messi': 10, 'Ronaldo': 7}

dict.setdefault()

The setdefault() gets a value of a specific key. If the key does not exist, the setdefault() method inserts a new key-value pair into the dictionary.

For example:

Output:

9
{'Bale': 9, 'Messi': 10, 'Lewandowski': 9, 'Ronaldo': 7}

dict.update()

The update() method inserts items to the dictionary. For example:

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
player_data.update({"Lewandowski": 9})print(player_data)

Output:

{'Lewandowski': 9, 'Ronaldo': 7, 'Messi': 10, 'Bale': 9}

dict.values()

The values() method returns a list of the dictionary values as a view object. For example:

player_data = {"Ronaldo": 7, "Messi": 10, "Bale": 9}
player_values = player_data.values()print(player_values)

Output:

dict_values([9, 7, 10])

You can convert a view object to a list with the list() method by replacing print(player_values) with print(list(player_values)).

How to Loop Through Python Dictionaries

You can loop through a dictionary using a for loop.

To be able to loop the dictionary, you need to use the dict.items() method.

In the following, you are going to loop through a student dictionary and print the entries.

To loop through a dictionary using a for loop:

for key, value in student.items():
print(key, value)

Output:

name Alice
graduated False
married False
age 23
hobbies ['Jogging', 'Gym', 'Boxing']

Dictionary Comprehensions

Python has a shorthand for looping through dictionaries, called dictionary comprehension.

In some situations, this shorthand can make your code more readable while saving some lines of code.

The syntax of dictionary comprehension looks like this:

{ key:value for (key,value) in dict if condition }

Let’s see some examples

Example 1 — Create a Dictionary from a List

Let’s create a dictionary based on a numbers list.

In the new dictionary, a number is a key and the value is the number as a string. Furthermore, let’s only include even numbers:

Output:

{2: '2', 4: '4', 6: '6', 8: '8'}

This works all fine but by using dictionary comprehension, this all can be achieved with one line!

Output:

{2: '2', 4: '4', 6: '6', 8: '8'}

Example 2 — Operating on an Existing Dictionary

Let’s see another example.

Here you have a dictionary and you want to create a new one based on it.

Let’s directly use a dictionary comprehension:

Output:

{'a': 3, 'b': 6, 'c': 9, 'd': 12, 'e': 15}

Common Python Dictionary Tasks

How to Sort a Dictionary by Value

As of Python 3.7, the insertion order is preserved in dictionaries. This means it is possible to sort a dictionary. Notice that older versions of Python do not support sorting dictionaries. This is because the dictionaries are unordered.

In Python 3.7 or higher, you can sort a dictionary by value using the sorted() function.

For example, let’s sort the data by participants’ ages (dictionary values):

Output:

{'Bob': 21, 'Alice': 23, 'David': 29, 'Charlie': 32}

At this point, you don’t need to worry about the lambda inside the sorted() function call. But if you want to learn what it does, read this article.

How to Sort a Dictionary by Key

As of Python 3.7, the insertion order is preserved in dictionaries. This means it is indeed possible to sort a dictionary.

Notice that the older versions of Python do not support sorting dictionaries. This is because the dictionaries are unordered by design.

You can sort a dictionary by key using the sorted() function.

For example, let’s sort a dictionary of name-age pairs alphabetically based on the name key:

Output:

{'Alice': 9, 'Bob': 12, 'Charlie': 5, 'David': 82}

How to Pretty-Print a Python Dictionary

During this guide, you have printed dictionaries into the console. But the result looks pretty messy because it is on a single line.

When you print larger dictionaries, it becomes infeasible to understand the result. This is where pretty printing can help you.

Python has a built-in pprint module. You can import it and use it to pretty-print a dictionary.

For example, let’s go back to the student dictionary:

Let’s print this dictionary into the console:

print(student)

The output looks ugly:

{'name': 'Alice', 'graduated': False, 'married': False, 'age': 23, 'hobbies': ['Jogging', 'Gym', 'Boxing']}

Let’s fix this with the pprint. Without digging too deep into the details, here is how the program looks:

This produces an output that is already better:

{'age': 23,
'graduated': False,
'hobbies': ['Jogging', 'Gym', 'Boxing'],
'married': False,
'name': 'Alice'}

If you want to make it even cleaner, you can use the json.dumps() method. But this assumes the dictionary is JSON-serializable.

Here is an example:

Here is the really nice looking output:

Conclusion

Python dictionary is a collection of key-value pairs. A dictionary is a very commonly used data type in Python.

You can create a dictionary by comma separating key-value pairs inside square brackets.

For example:

example_dictionary = { "Ronaldo": 7, "Bale": 9, "Messi": 10 }

With a dictionary it is easy to:

  • Read data
  • Update data
  • Remove data

And much more.

There are also a lot of built-in dictionary methods that can save you time when dealing with Python dictionaries.

Thanks for reading. I hope you enjoy it.

Happy coding!

Become a Top Coder

Did you like this article?

Become a member at Medium.com to read top stories by experts in the field.

Disclaimer: By joining via the provided link, I earn a small commission at no extra cost for you :)

Further Reading

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Artturi Jalli

Artturi Jalli

I built a blog from 0 to 350k+ monthly visits in 16 months without SEO.