Python Dictionary Tutorial

Click to share! ⬇️

dictionaries in python

Dictionaries in Python allow programmers to associate pieces of related information. Each piece of information in a dictionary is stored as a key-value pair. These are similar to associative arrays in other popular programming languages. To access the value in a dictionary, you provide the associated key. You can loop over dictionaries while accessing all of the values, keys, or the entire key-value pair. In this tutorial, we’ll take a look at how to create a dictionary, how to get the value of a key, how to put a dictionary in a list, how to add new key-value pairs, how to modify values, and more.

python dictionary type

How To Create A Dictionary

To create a dictionary in Python, you can make use of the curly braces { }. Inside of the curly braces, a colon : is used to associate various key-value pairs.

Making a dictionary

player_0 = {'level': 'novice', 'points': 7}

python make a dictionary

Getting The Value Of A Key

There are a couple of ways to use the values stored in dictionaries. To access the value associated with a specific key, you can specify the name of the dictionary and then place the key inside a set of square brackets [ ]. If you try to access a key that does not exist, Python will output a KeyError message. There is also a get() method, which returns None instead of an error if the key doesn’t exist. It is also possible to specify a default value to use if the key is not in the dictionary.

Accessing the value associated with a given key

player_0 = {'level': 'novice', 'points': 7}

pycharm dictionary output

Using the get() method to access a value

player_0 = {'level': 'novice'}
player_level = player_0.get('level')
player_points = player_0.get('points', 0)

python dictionary get method

Dictionaries Inside Lists

It is possible to define a dictionary and then store it inside of a list. This is what is known as Nesting.

Storing dictionaries within a list

# Start with an empty list.
profiles = []
# Make a new profile, and add them to the list.
new_profile = {
    'last': 'Diaz',
    'first': 'Guillermo',
    'profilename': 'gDiaz',
# Make another new profile, and add them as well.
new_profile = {
    'last': 'Rezende',
    'first': 'Pedro',
    'profilename': 'pRezende',
# Show all information about each profile.
for profile_dict in profiles:
    for k, v in profile_dict.items():
        print(f"{k}: {v}")
last: Diaz
first: Guillermo
profilename: gDiaz
last: Rezende
first: Pedro
profilename: pRezende

dictionary nest inside list

Defining a list of dictionaries without using append()

# Define a list of profiles, where each profile
# is represented by a dictionary.
profiles = [
        'last': 'Diaz',
        'first': 'Guillermo',
        'profilename': 'eDiaz',
        'last': 'Rezende',
        'first': 'Pedro',
        'profilename': 'mRezende',
# Show all information about each profile.
for profile_dict in profiles:
    for k, v in profile_dict.items():
        print(f"{k}: {v}")
last: Diaz
first: Guillermo
profilename: eDiaz
last: Rezende
first: Pedro
profilename: mRezende

python data in dictionary

Adding New Key-Value Pairs

The only limit to how many key-value pairs you can store in a dictionary is determined by the amount of memory on the machine the Python program is running on. Of course, you’ll likely never need that many key-value pairs, but it’s good to know you could have millions of them if you so desired. You can add a new key-value pair to an existing dictionary by giving the name of the dictionary and the new key in square brackets. Then, set the new value into that expression. You can start with an empty dictionary and add key-value pairs as needed.

Adding a key-value pair

player_0 = {'level': 'novice', 'points': 7}
player_0['x'] = 0
player_0['y'] = 25
player_0['speed'] = 1.5

The above code may also be written as a dictionary literal like so.

player_0 = {'level': 'novice', 'points': 7, 'x': 0, 'y': 25, 'speed': 1.5}

Adding to an empty dictionary

player_0 = {}
player_0['level'] = 'novice'
player_0['points'] = 7

How To Modify Values

Since a dictionary is mutable, you can change the value associated with any key in the dictionary. Provide the name of the dictionary and
enclose the key in square brackets, then provide the new value for that key to modify the original value.

Modifying values in a dictionary

player_0 = {'level': 'novice', 'points': 7}
# Change the player's level and point value.
player_0['level'] = 'intermediate'
player_0['points'] = 10
{'level': 'novice', 'points': 7}
{'level': 'intermediate', 'points': 10}

modify python dictionary

Removing key-value pairs

To remove a key-value pair from a dictionary, you can use the del keyword. Use the del keyword, then provide the dictionary name, followed by the key in square brackets. This will remove the key and its associated value from the dictionary.

Deleting a key-value pair

player_0 = {'level': 'novice', 'points': 7}
del player_0['points']
{'level': 'novice', 'points': 7}
{'level': 'novice'}

Storing a list inside a dictionary allows you to associate more than one value with each key.
Storing lists in a dictionary

# Store multiple games for each person.
fav_games = {
    'Pedro': ['Outer Wilds', 'Disco Elysium'],
    'Sean': ['Baba Is You'],
    'Daniel': ['Sekiro', 'Star Wars Jedi'],
    'Guillermo': ['Control', 'Dragon Quest Builders 2'],
# Show all responses for each person.
for name, games in fav_games.items():
    print(f"{name}: ")
    for game in games:
        print(f"- {game}")
- Outer Wilds
- Disco Elysium
- Baba Is You
- Sekiro
- Star Wars Jedi
- Control
- Dragon Quest Builders 2

python nested lists dictionaries

Dictionary of dictionaries

You can store a dictionary inside another dictionary. In this case, each value associated with a key is itself a dictionary.

Storing dictionaries in a dictionary

profiles = {
    'smcloughlin': {
        'first': 'Sean',
        'last': 'McLoughlin',
        'gender': 'male',
    'prezende': {
        'first': 'Pedro',
        'last': 'Rezende',
        'gender': 'male',
for profilename, profile_dict in profiles.items():
    print("nUsername: " + profilename)
    full_name = profile_dict['first'] + " "
    full_name += profile_dict['last']
    gender = profile_dict['gender']
    print(f"tFull name: {full_name.title()}")
    print(f"tgender: {gender.title()}")
Username: smcloughlin
	Full name: Sean Mcloughlin
	gender: Male

Username: prezende
	Full name: Pedro Rezende
	gender: Male

python dictionaries in a dictionary

Avoid Excessive Nesting

Nesting can be very useful in some situations. The downside is that this can make the code more complex than what is ideal. If you find yourself nesting items deeper than the examples here, then there are probably better ways of managing your data. One option is to use Classes to handle data management.

Looping through a dictionary

There are three different ways to loop over a dictionary. The first is to loop through all of the values in the dictionary. The next is to loop over all of the keys. The last is to loop over all of the key-value pairs together. Different problems require different approaches. As you add key-value pairs to a dictionary, it will keep track of the order in which they were added. To process the data in a different order, you can sort the keys in the loop.

Looping through all key-value pairs

# Store people's favorite games.
fav_games = {
    'George': 'Crash Bandicoot',
    'Alex': 'Super Smash Bros',
    'Sarah': 'Legend Of Zelda',
    'Allison': 'Pong',

store key value pairs in dictionary

# Show each person's favorite game.
for name, game in fav_games.items():
    print(f"{name}: {game}")
George: Crash Bandicoot
Alex: Super Smash Bros
Sarah: Legend Of Zelda
Allison: Pong

Looping through all the keys

# Show everyone who's taken the survey.
for name in fav_games.keys():

Looping through all the values

# Show all the games that have been chosen.
for game in fav_games.values():

Looping through all the keys in reverse order

# Show each person's favorite game,
# in reverse order by the person's name.
for name in sorted(fav_games.keys(), reverse=True):
    print(f"{name}: {fav_games[name]}")
Sarah: Legend Of Zelda
George: Crash Bandicoot
Allison: Pong
Alex: Super Smash Bros

Checking The Length Of A Dictionary

You can find the number of key-value pairs in a dictionary by using the len() function.

Determine a dictionary’s length

num_responses = len(fav_games)

Dictionary Comprehensions

Just like a list has the feature of comprehension, so too do dictionaries. A comprehension is just a compact way of creating a dictionary. To make a dictionary comprehension, define an expression for the key-value pairs you want to make. Then write a for loop to generate the values that will feed into this expression. The zip() function matches each item in one list to each item in a second list. It can be used to make a dictionary from two lists.

Using a loop to create a dictionary

cubes = {}
for x in range(5):
    cubes[x] = x ** 3

Using a loop to create a dictionary

Using a dictionary comprehension

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

Using a dictionary comprehension

Using zip() to make a dictionary

veggies = ['pepper', 'broccoli', 'spinach', 'potato']
fruits = ['apple', 'orange', 'peach', 'plum']
combos = {key: key_2 for key, key_2 in zip(veggies, fruits)}

Using zip to make a dictionary

Creating thousands of dictionaries

To create a large number of dictionaries at once, you can use a loop like so.

players = []
# Make a thousand novice players, worth 3 points
# each. Have them all start in one row.
for player_num in range(1000):
    new_player = {}
    new_player['level'] = 'novice'
    new_player['points'] = 3
    new_player['x'] = 20 * player_num
    new_player['y'] = 0

# Show the list contains a thousand players.
num_players = len(players)
print("Number of players created:")
Number of players created:

Learn More About Dictionaries In Python

Dictionaries In Python Summary

Python’s dictionary type is a hashed key-value structure. This is comparable to associative arrays in other languages like PHP and JavaScript. A dictionary is created using curly braces with an opening curly brace and a closing curly brace. Inside of the curly braces is the key-value pairs. Each of the key-value pairs has a key on the left, a value on the right and they’re separated by a colon. The pairs themselves are separated by commas within the structure sets. You can also create the dictionary using the dictionary constructor and keyword arguments. Keys and values may be any type. Keys must be immutable. Strings and numbers can always be keys. The items() method returns a view of key-value pairs. The keys() method returns a view of dictionary keys and the values() method gives us just a list of the values. A dictionary is indexed by its keys so you can easily pick a particular element. If you try to access a key that doesn’t exist you’ll get a key error exception. On the other hand, you can use the get() method to return a value when you don’t know if the key exists. Python’s dictionary type is both simple and useful, and you’ll see many examples of it in code for common Python projects.

Click to share! ⬇️