← Back to Python Course | Chapter 6: Data Structures | Lesson 6 of 12

Python Dictionaries

A dictionary is like a real dictionary or phone book: you look something up by its name (the key) and get its information (the value). It is great for keeping labeled facts together.
Syntax
python
dict_name = {key1: value1, key2: value2}
dict_name[key]

What is a Dictionary?

A dictionary maps unique, immutable keys (strings, numbers, or tuples) to values, and since Python 3.7 insertion order is preserved when you iterate.

It's the natural structure for anything you'd otherwise model as a lookup table, like a username-to-user-record mapping.

Example: What is a Dictionary?

python
user = {"name": "Alex", "age": 30}
print(user)

Accessing and Modifying Values

Reading my_dict[key] raises KeyError if the key is absent, while writing my_dict[key] = value either updates an existing entry or creates a new one -- there's no separate insert operation, assignment handles both cases.

Example: Accessing and Modifying Values

python
user = {"name": "Alex"}
print(user["name"])  # raises KeyError if "name" were missing
user["name"] = "Sam"  # updates the existing key
print(user)

Adding and Deleting Items

Assigning to a new key adds it to the dictionary; del my_dict[key] removes an entry and raises KeyError if it's missing, so checking key in my_dict first (or using .pop(key, None)) avoids crashing on absent keys.

Example: Adding and Deleting Items

python
user = {"name": "Alex"}
user["age"] = 30  # adds a new key
del user["age"]  # removes it
print(user)

Iterating Through a Dictionary

Iterating a dictionary directly (for k in my_dict) yields its keys; .values() yields just the values and .items() yields (key, value) pairs, which is the most common form when you need both during the loop.

Example: Iterating Through a Dictionary

python
user = {"name": "Alex", "age": 30}
for key, value in user.items():  # yields both key and value together
    print(key, value)

Dictionary Length and Duplicate Keys

Dictionary keys are inherently unique -- assigning to an existing key overwrites its value rather than creating a duplicate entry -- and len(my_dict) counts key-value pairs, not individual keys and values separately.

Example: Dictionary Length and Duplicate Keys

python
user = {"name": "Alex"}
user["name"] = "Sam"  # overwrites, not a duplicate
print(user)
print(len(user))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading a missing key with d["age"], which raises KeyError; use d.get("age") or check "age" in d.
  2. Using a list as a key, as in d[[1, 2]] = "x", which raises TypeError because keys must be hashable.
  3. Repeating a key in a dictionary literal, as in {"a": 1, "a": 2}, where the last value silently wins and the first is lost.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.