Python Dictionary — A Complete Guide

Learn everything about dictionaries in Python

Python dictionary
Image design by Elias Ervast

How to Define a Python Dictionary

1. Comma-Separated Key-Value Pairs

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

3. Define a Dictionary Using Keyword Arguments

4. Create a Dictionary Incrementally

How to See the Contents of a Python Dictionary

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

How to Access Python Dictionary Values

student["name"]
print(student["name"])
Alice
student["haircolor"]
KeyError: 'haircolor'

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

student["haircolor"] = "Red"
print(student["haircolor"])
Red

How to Update a Key-Value Pair In a Dictionary

student["age"] = 24

How to Delete a Key-Value Pair From a Dictionary

del student["haircolor"]
print(student)
{'name': 'Alice', 'graduated': False, 'married': False, 'age': 23, 'hobbies': ['Jogging', 'Gym', 'Boxing']}

Valid Python Dictionary Key Types

Restrictions on Dictionary Keys

Restrictions on Dictionary Values

Dictionary Operators

In Statement

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

Len() Function

print(len(student))
5

Python Dictionary Methods

dict.clear()

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

dict.copy()

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

dict.fromkeys()

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

dict.get()

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

dict.items()

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

dict.keys()

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

dict.pop()

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

dict.popitem()

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

dict.setdefault()

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

dict.update()

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

dict.values()

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

How to Loop Through Python Dictionaries

for key, value in student.items():
print(key, value)
name Alice
graduated False
married False
age 23
hobbies ['Jogging', 'Gym', 'Boxing']

Dictionary Comprehensions

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

Example 1 — Create a Dictionary from a List

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

Example 2 — Operating on an Existing Dictionary

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

Common Python Dictionary Tasks

How to Sort a Dictionary by Value

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

How to Sort a Dictionary by Key

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

How to Pretty-Print a Python Dictionary

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

Conclusion

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

Become a Top Coder

Further Reading

I’m a tech expert, entrepreneur, and software engineer from Finland. I write about programming, tech, and science. Visit my blog at www.codingem.com.