LearnContact
Lesson 1828 min read

Dictionaries

Learn how Python dictionaries store data as key-value pairs and how to access, update, and iterate over them safely.

Introduction

A dictionary is one of the most useful data structures in Python. Instead of storing values in order like a list, a dictionary stores data as key-value pairs, so you can look up a value directly by its meaningful name instead of by its numeric position.

Think of a real dictionary book: you look up a word (the key) to find its definition (the value). Python dictionaries work the same way — you look up a key to instantly retrieve its associated value.

What You Will Learn
  • How to create dictionaries using key:value pairs.
  • How to access values safely with .get() versus bracket notation.
  • Why dictionary keys must be hashable and immutable.
  • Common dictionary methods like keys(), values(), items(), update(), pop(), and setdefault().
  • How to iterate over a dictionary and check if a key exists.
  • How to work with nested dictionaries.

Creating Dictionaries

A dictionary is written with curly braces {}, containing key:value pairs separated by commas. Keys map to values, and every key in a dictionary must be unique.

creating_dict.py
student = {
    "name": "Alex",
    "age": 16,
    "grade": "10th"
}

print(student)
print(type(student))

empty_dict = {}
print(type(empty_dict))
Output
{'name': 'Alex', 'age': 16, 'grade': '10th'}
<class 'dict'>
<class 'dict'>
Unlike Sets, {} Works Here

Unlike sets, an empty {} always creates an empty dictionary, not an empty set. This is because dictionaries were Python's original use for curly braces.

Accessing Values

You can retrieve a value using square brackets with its key, or the safer .get() method, which lets you supply a default value instead of crashing when the key is missing.

accessing_values.py
student = {"name": "Alex", "age": 16}

print(student["name"])
print(student.get("age"))
print(student.get("school"))
print(student.get("school", "Not Enrolled"))
Output
Alex
16
None
Not Enrolled
bracket_error.py
student = {"name": "Alex"}
print(student["school"])
Output
KeyError: 'school'
Bracket Access vs get()

Use square brackets when you are certain the key exists and a missing key should be treated as a bug. Use .get() when a missing key is a normal possibility you want to handle gracefully.

Keys Must Be Hashable

Dictionary keys must be hashable, which in practice means they must be immutable — strings, numbers, and tuples work fine as keys, but lists, sets, and other dictionaries do not.

unhashable_key.py
coordinates = {}
coordinates[(10, 20)] = "Point A"   # tuple key works fine
print(coordinates)

try:
    coordinates[[10, 20]] = "Point B"  # list key fails
except TypeError as e:
    print("Error:", e)
Output
{(10, 20): 'Point A'}
Error: unhashable type: 'list'

Values, on the other hand, can be absolutely anything — strings, numbers, lists, or even other dictionaries.

Common Dictionary Methods

keys()

Returns a view of all the keys in the dictionary.

values()

Returns a view of all the values in the dictionary.

items()

Returns a view of (key, value) pairs.

update()

Merges another dictionary's keys and values into this one.

pop(key)

Removes a key and returns its value.

setdefault(key, default)

Returns the key's value if it exists, otherwise sets and returns the default.

dict_methods.py
student = {"name": "Alex", "age": 16}

print(list(student.keys()))
print(list(student.values()))
print(list(student.items()))

student.update({"grade": "10th", "age": 17})
print(student)

removed_age = student.pop("age")
print("Removed age:", removed_age)
print(student)

school = student.setdefault("school", "Unknown")
print(school)
print(student)
Output
['name', 'age']
['Alex', 16]
[('name', 'Alex'), ('age', 16)]
{'name': 'Alex', 'age': 17, 'grade': '10th'}
Removed age: 17
{'name': 'Alex', 'grade': '10th'}
Unknown
{'name': 'Alex', 'grade': '10th', 'school': 'Unknown'}

Iterating Over a Dictionary

Looping directly over a dictionary gives you its keys. To get both the key and value together, loop over .items() instead.

iterating_dict.py
prices = {"apple": 40, "banana": 20, "cherry": 150}

for fruit in prices:
    print(fruit)

print("---")

for fruit, price in prices.items():
    print(f"{fruit}: ₹{price}")
Output
apple
banana
cherry
---
apple: ₹40
banana: ₹20
cherry: ₹150

Checking Key Existence

Use the in keyword to check whether a key exists before accessing it, which avoids KeyError crashes.

checking_keys.py
student = {"name": "Alex", "age": 16}

if "age" in student:
    print("Age:", student["age"])

if "school" not in student:
    print("School is not recorded yet.")
Output
Age: 16
School is not recorded yet.
in Checks Keys, Not Values

By default, "x in my_dict" checks only the keys. To check whether a value exists, use "x in my_dict.values()" instead.

Nested Dictionaries

Dictionary values can themselves be dictionaries, which is extremely useful for representing structured, real-world data such as records with multiple related fields.

nested_dict.py
students = {
    "s101": {"name": "Alex", "age": 16},
    "s102": {"name": "Priya", "age": 17}
}

print(students["s101"]["name"])
print(students["s102"]["age"])

for student_id, info in students.items():
    print(f"{student_id}: {info['name']}, age {info['age']}")
Output
Alex
17
s101: Alex, age 16
s102: Priya, age 17

Common Mistakes

Avoid These Mistakes
  • Accessing a missing key with square brackets and causing an unhandled KeyError — use .get() when a key might be missing.
  • Trying to use a list, set, or dictionary as a key — keys must be hashable and immutable.
  • Forgetting that dictionaries preserve insertion order (Python 3.7+) but are still looked up by key, not position.
  • Confusing d.keys() iteration with d.items() when you actually need both key and value.
  • Overwriting a key accidentally by assigning to it again without checking if it already holds important data.

Best Practices

  • Use .get() with a default value when a key's presence is not guaranteed.
  • Use descriptive, consistent key names, ideally strings.
  • Use "in" to check key existence before accessing a potentially missing key.
  • Prefer .items() when you need both keys and values in a loop.
  • Keep nested dictionaries shallow and well-documented so the structure stays easy to follow.

Frequently Asked Questions

Do dictionaries preserve insertion order?

Yes, as of Python 3.7, dictionaries maintain the order in which keys were inserted, though you should still access items by key, not position.

Can two keys be the same in a dictionary?

No. Keys must be unique — assigning a value to an existing key overwrites the previous value instead of creating a duplicate.

What happens if I use d[key] = value on a key that already exists?

It updates the existing value for that key rather than creating a new entry.

Is a dictionary the same as a JSON object?

They are very similar in structure. Python dictionaries are commonly converted to and from JSON using the json module, which you will see in a later lesson.

Can dictionary values be lists or other dictionaries?

Yes. Only keys must be hashable and immutable — values can be any data type, including lists, tuples, or nested dictionaries.

Key Takeaways

  • A dictionary stores data as key:value pairs and is created with {}.
  • .get() safely returns a default instead of raising KeyError for a missing key.
  • Keys must be hashable and immutable; values can be any type.
  • keys(), values(), items(), update(), pop(), and setdefault() are essential dictionary methods.
  • Use "in" to check key existence, and .items() to loop over keys and values together.

Summary

Dictionaries let you store and retrieve data by meaningful keys instead of numeric positions, making them ideal for representing structured, real-world information like user profiles, settings, or records.

Next, you will learn how to control the flow of your program using conditional statements — if, elif, and else.

Lesson 18 Completed
  • You can create and access dictionary values safely.
  • You understand which data types can be used as keys.
  • You know the core dictionary methods and how to iterate over a dictionary.
  • You are ready to learn conditional statements.
Next Lesson →

Conditional Statements (if, elif, else)