beginnerPython Framework β€’ Core Concepts

Dictionaries: Key-Value Pairs

Join 1.2k+ learners

Introduction to Dictionaries

A dictionary is a fast, flexible container that maps unique keys to values. Unlike lists, which are indexed by numbers (0, 1, 2...), dictionaries are indexed by keys, which can be strings, numbers, or even tuples. They are the backbone of data representation in Python.

Python
# A simple contact book contacts = { "Alice": "555-1234", "Bob": "555-9876" } # Lookup by name (key) print(contacts["Alice"]) # "555-1234"

Dictionary Visualization

Key (Name) β†’ Value (Phone)
{
"Alice":"555-1234",
"Bob":"555-9876"
}
πŸ’‘ Access values using Key (Name) β†’ Value (Phone)["key"] β€” hover over entries to see access syntax

Creating Dictionaries

You can create dictionaries using the literal syntax {} or the dict() constructor. The literal syntax is faster and more common.

Python
# Literal syntax (Recommended) student = {"name": "Alice", "age": 25} # dict() constructor car = dict(brand="Toyota", model="Corolla") # Empty dictionary empty = {}

Dictionary Visualization

student = {...}
{
"name":"Alice",
"age":25
}
πŸ’‘ Access values using student = {...}["key"] β€” hover over entries to see access syntax

Accessing Values

Access values using square brackets [key]. If you're unsure if a key exists, use .get(key) to avoid errors. .get() returns None (or a default) if the key is missing.

Python
student = {"name": "Alice", "age": 25} # Direct access print(student["name"]) # "Alice" # print(student["grade"]) # KeyError! # Safe access with .get() grade = student.get("grade") # None score = student.get("score", 0) # 0 (default)

Dictionary Visualization

student.get("name") β†’ "Alice"
{
"name":"Alice",
"age":25
}
πŸ’‘ Access values using student.get("name") β†’ "Alice"["key"] β€” hover over entries to see access syntax

Updating & Adding

Dictionaries are mutable. Assign a value to a key to add it (if new) or update it (if it exists).

Python
student = {"name": "Alice", "age": 25} # Add new key student["grade"] = "A" # Update existing key student["age"] = 26 print(student) # {'name': 'Alice', 'age': 26, 'grade': 'A'}

Dictionary Visualization

Modified age, added grade
{
"name":"Alice",
"age":26,Modified age, added grade["age"] β†’ 26
"grade":"A"Modified age, added grade["grade"] β†’ "A"
}
πŸ’‘ Access values using Modified age, added grade["key"] β€” hover over entries to see access syntax

Removing Items

Use .pop(key) to remove a key and return its value. 'del' deletes a key without returning. .popitem() removes the last inserted item (LIFO). .clear() wipes the dictionary.

Python
student = {"name": "Alice", "age": 26, "grade": "A"} # Remove and get value grade = student.pop("grade") # "A" # Delete specific key del student["age"] # Remove last item item = student.popitem() # ('name', 'Alice') print(student) # {}

Dictionary Visualization

After popping 'grade'
{
"name":"Alice",
"age":26
}
πŸ’‘ Access values using After popping 'grade'["key"] β€” hover over entries to see access syntax

Iteration

You can loop over a dictionary's keys, values, or both. Looping over the dictionary directly yields keys.

Python
data = {"a": 1, "b": 2} # Loop over keys (default) for key in data: print(key) # "a", "b" # Loop over keys and values for key, val in data.items(): print(f"{key}: {val}")

Dictionary Visualization

for k, v in data.items()
{
"a":1,
"b":2
}
πŸ’‘ Access values using for k, v in data.items()["key"] β€” hover over entries to see access syntax

Dictionary Methods

.keys(), .values(), and .items() return view objects. These views update dynamically if the dictionary changes.

Python
d = {"x": 10, "y": 20} keys = d.keys() # dict_keys(['x', 'y']) vals = d.values() # dict_values([10, 20]) items = d.items() # dict_items([('x', 10), ('y', 20)])

Dictionary Visualization

.keys(), .values(), .items()
{
"x":10,
"y":20
}
πŸ’‘ Access values using .keys(), .values(), .items()["key"] β€” hover over entries to see access syntax

Nested Dictionaries

Dictionaries can contain other dictionaries. This is great for representing complex hierarchical data like JSON responses or database records.

Python
students = { "Alice": {"age": 25, "grade": "A"}, "Bob": {"age": 22, "grade": "B"} } # Access nested value print(students["Alice"]["grade"]) # "A"

Real-World Examples

Dictionaries are everywhere: user profiles, configuration settings, counting frequencies, and caching results.

Python
# 1. Frequency Counter text = "apple banana apple" counts = {} for word in text.split(): counts[word] = counts.get(word, 0) + 1 # {'apple': 2, 'banana': 1} # 2. Config Settings config = { "theme": "dark", "notifications": True, "volume": 80 }

Dictionary Visualization

Word frequency count
{
"apple":2,
"banana":1
}
πŸ’‘ Access values using Word frequency count["key"] β€” hover over entries to see access syntax

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor

Visual Lab

Dictionary Visualization

student = {'name': 'Alice', ...}
{
"name":"Alice",
"age":25,
"city":"NYC"
}
πŸ’‘ Access values using student = {'name': 'Alice', ...}["key"] β€” hover over entries to see access syntax

New Challenge available!

Master Dictionaries: Key-Value Pairs with a hands-on task.