Python · Dictionaries

Complete Guide to Python Dictionaries

A dictionary is a collection of key : value pairs. It lets you map one piece of information (the key) to another (the value), like a real dictionary: a word → its meaning.

1. Creating a Dictionary

1.1 Basic Dictionary

student = {
    "name": "Maria",
    "age": 21,
    "grade": "A"
}

1.2 Empty Dictionary

empty_dict = {}

1.3 Using dict() Constructor

car = dict(brand="Tesla", model="Model 3", year=2023)
print(car)

Output:

{'brand': 'Tesla', 'model': 'Model 3', 'year': 2023}

1.4 Keys & Values

Keys can be strings, numbers, or tuples (immutable types). Values can be any type.

data = {
    1: "one",
    2.5: "two point five",
    (3, 4): "tuple key"
}

Try it out:

2. Accessing Values

Access values using their keys.

person = {
    "name": "Alex",
    "age": 25,
    "country": "Lithuania"
}

print(person["name"])   # Alex
print(person["age"])    # 25

Accessing a missing key causes a KeyError:

print(person["height"])   # ❌ KeyError

2.1 Safe Access with get()

print(person.get("height"))         # None
print(person.get("height", 0))      # 0 (default value)

Try it out:(you have to define "person")

3. Adding & Updating Items

3.1 Add New Key-Value Pair

person["height"] = 180  # adds new key
print(person)

3.2 Update Existing Key

person["age"] = 26  # updates value (define person first to test)
print(person)

4. Removing Items

person = {"name": "Alex", "age": 25, "country": "Lithuania"}

4.1 pop() – Remove by Key

age = person.pop("age")
print(age)     # 25
print(person)  # {"name": "Alex", "country": "Lithuania"}

4.2 del Statement

del person["country"]
print(person)

4.3 clear() – Remove All Items

person.clear()
print(person)  # {}

5. Looping Through Dictionaries

5.1 Loop Through Keys

person = {"name": "Alex", "age": 25, "country": "Lithuania"}

for key in person:
    print(key)

5.2 Loop Through Values

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

5.3 Loop Through Key-Value Pairs

for key, value in person.items():
    print(key, "->", value)

6. Checking Key Existence & Length

6.1 Check if Key Exists

person = {"name": "Alex", "age": 25}

if "name" in person:
    print("Name exists")

6.2 Dictionary Length

print(len(person))  # number of key-value pairs

7. Useful Dictionary Methods

person = {"name": "Alex", "age": 25, "country": "Lithuania"}

7.1 keys() – All Keys

print(person.keys())   # dict_keys(['name', 'age', 'country'])

7.2 values() – All Values

print(person.values()) # dict_values(['Alex', 25, 'Lithuania'])

7.3 items() – Key-Value Pairs

print(person.items())  # dict_items([('name', 'Alex'), ('age', 25), ...])

7.4 update() – Merge / Update

person.update({"age": 30, "city": "Vilnius"})
print(person)

8. Nested Dictionaries

You can store dictionaries inside dictionaries to represent structured data.

users = {
    "user1": {
        "name": "Alex",
        "age": 25
    },
    "user2": {
        "name": "Maria",
        "age": 22
    }
}

print(users["user1"]["name"])  # Alex

Looping Through Nested Dictionaries

for username, data in users.items():
    print(username)
    for key, value in data.items():
        print("  ", key, ":", value)

9. Dictionaries with Lists

Dictionaries can hold lists as values.

classroom = {
    "students": ["Alex", "Maria", "John"],
    "grades": [90, 85, 88]
}

print(classroom["students"][0])  # Alex
print(classroom["grades"][1])    # 85

10. Copying Dictionaries

Be careful: assigning with = copies the reference, not the data.

a = {"x": 1, "y": 2}
b = a      # both refer to the same dictionary
b["x"] = 99

print(a)  # {"x": 99, "y": 2}

Use copy() or dict() to make a shallow copy:

a = {"x": 1, "y": 2}

b = a.copy()
# or b = dict(a)

b["x"] = 99

print(a)  # {"x": 1, "y": 2}
print(b)  # {"x": 99, "y": 2}

11. Dictionary Comprehensions

Create dictionaries from loops in a compact way.

11.1 Basic Comprehension

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

11.2 With Condition

even_squares = {x: x * x for x in range(10) if x % 2 == 0}
print(even_squares)

12. Using Dictionaries for Counting

A common use is counting word frequency.

sentence = "python is easy and python is powerful".split()
count = {}

for word in sentence:
    count[word] = count.get(word, 0) + 1

print(count)

Output:

{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'powerful': 1}

13. Merging Dictionaries

13.1 Python 3.9+ Using |

a = {"x": 1}
b = {"y": 2}

combined = a | b
print(combined)  # {"x": 1, "y": 2}

13.2 Older Versions Using Unpacking

a = {"x": 1}
b = {"y": 2}

combined = {**a, **b}
print(combined)

14. Real-World Example: Simple User Database

users = {}

while True:
    username = input("Enter username (or 'exit'): ")

    if username == "exit":
        break

    age = int(input("Enter age: "))
    country = input("Enter country: ")

    users[username] = {
        "age": age,
        "country": country
    }

print(users)

15. Common Dictionary Mistakes

MistakeWrongCorrect
Accessing missing key directly
age = person["age"]  # KeyError if missing
age = person.get("age", 0)
Copying dictionary incorrectly
b = a  # both refer to same data
b = a.copy()
Looping wrong over items
for k, v in person:
    print(k, v)  # ❌
for k, v in person.items():
    print(k, v)  # ✅

16. When to Use Dictionaries & Summary

Use dictionaries when you need:

In this guide, you learned how to:

Dictionaries are one of the most powerful tools in Python and appear everywhere in real projects.