Python Dictionary Documentation Explained (Python Docs 5.5) โ€” dict(), get(), Comprehensions & Examples

๐Ÿ“– Based on Python 3 official docs 5.5 โ€” explained like a friend, with extra examples added
Python Beginner Data Structures Official Docs Updated June 2026

This page explains the official Python Dictionary documentation (Python Docs 5.5) in simple language. If the official Python documentation feels overwhelming, this guide breaks down dictionaries, key-value pairs, dict(), get(), list(d), sorted(d), dictionary comprehensions, and nested dictionaries with beginner-friendly explanations and practical examples.

By the end of this guide, you'll understand key-value pairs, dictionary creation, accessing values, get(), del, dictionary methods, nested dictionaries, dictionary comprehensions, and when to use dictionaries in real Python projects.

What is a Python Dictionary? (Python Docs 5.5 Explained)

Think of it as a labeled storage system. Instead of looking things up by position (index 0, 1, 2...) like a list, you look them up by a meaningful label โ€” a key.

person = {
    "name" : "Joe"โ† key (immutable) : value (any type)
    "age" : 37โ† keys must be unique within a dict
    "city" : "England"โ† values can be any Python type
}โ† curly braces wrap the whole thing
Indexed by keys Look up values by their key โ€” not by position
Mutable Add, update, and delete after creation
Keys are unique Same key twice? Second value silently overwrites first
Ordered Python 3.7+ preserves insertion order
๐Ÿ“˜ From the Python docs

Keys can be any immutable type โ€” strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples. You can't use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

Creating a Python Dictionary (dict) โ€” 3 Official Ways

Three ways โ€” the docs show all three, and each has its moment:

PythonKiddo + Python docs
# Method 1 โ€” curly braces (most common)
tel = {'jack': 4098, 'sape': 4139}
print(tel)  # {'jack': 4098, 'sape': 4139}

# Method 2 โ€” dict() from a list of (key, value) tuples
# This is straight from the Python docs ยง5.5
tel2 = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print(tel2)  # {'sape': 4139, 'guido': 4127, 'jack': 4098}

# Method 3 โ€” dict() with keyword arguments (keys become strings)
# From the Python docs: "easier when keys are simple strings"
tel3 = dict(sape=4139, guido=4127, jack=4098)
print(tel3)  # {'sape': 4139, 'guido': 4127, 'jack': 4098}

# Empty dictionary
empty = {}
empty2 = dict()  # same thing
When to use which: curly braces for most cases. dict([tuples]) when your data is already in a list of pairs (e.g. from a CSV or API). dict(keyword=val) when keys are simple strings and you want it to look clean.

Accessing Dictionary Values โ€” dict[key] vs get()

The main operation on a dictionary is storing a value with a key and then extracting the value given the key. Two ways to read โ€” and the difference matters:

PythonPython docs example
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127

# Direct access โ€” fast, but crashes if key doesn't exist
print(tel['jack'])    # 4098

# This would crash:
# print(tel['irv'])   # KeyError: 'irv'
# Traceback (most recent call last):
#   File "", line 1, in 
# KeyError: 'irv'

# .get() โ€” safe access, returns None if key missing
print(tel.get('irv'))           # None
print(tel.get('irv', 'N/A'))    # N/A  โ† custom default
From the Python docs: extracting a value for a non-existent key by subscripting (d[key]) raises a KeyError. To avoid this, use the get() method instead โ€” it returns None (or a specified default value) if the key is not in the dictionary.

Kiddo extra โ€” real-world version

PythonKiddo example
user = {"name": "Palak", "plan": "free", "verified": True}

# Safe pattern before accessing
if "email" in user:
    print(user["email"])
else:
    print("Email not set")

# Or just use .get() with a default
email = user.get("email", "not provided")
print(email)  # not provided

Add, Update, and Delete Dictionary Items

Dictionaries are mutable โ€” all three operations use simple syntax. If you store using a key that is already in use, the old value is forgotten.

PythonPython docs example
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127          # ADD new key
print(tel)
# {'jack': 4098, 'sape': 4139, 'guido': 4127}

del tel['sape']              # DELETE with del
tel['irv'] = 4127            # ADD after delete
print(tel)
# {'jack': 4098, 'guido': 4127, 'irv': 4127}

# UPDATE โ€” same syntax as ADD, just use existing key
tel['jack'] = 9999           # old value 4098 is forgotten
print(tel['jack'])           # 9999

Kiddo extra โ€” .pop() and .update()

PythonKiddo example
person = {"name": "Palak", "age": 20, "city": "Delhi"}

# .pop() removes AND returns the value
removed = person.pop("city")
print(removed)   # Delhi
print(person)    # {"name": "Palak", "age": 20}

# .update() merges multiple keys at once
person.update({"age": 21, "city": "Mumbai", "course": "BCA"})
print(person)
# {'name': 'Palak', 'age': 21, 'city': 'Mumbai', 'course': 'BCA'}

list(d) and sorted(d) Explained

Two built-in functions that work directly on dictionaries โ€” no method call, no .keys() needed:

PythonPython docs example
tel = {'jack': 4098, 'guido': 4127, 'irv': 4127}

# list(d) โ€” all keys as a list, in insertion order
list(tel)
# ['jack', 'guido', 'irv']

# sorted(d) โ€” all keys sorted alphabetically
sorted(tel)
# ['guido', 'irv', 'jack']
๐Ÿ“˜ From the Python docs

Performing list(d) on a dictionary returns a list of all the keys in insertion order. If you want them sorted, use sorted(d) instead.

Kiddo extra โ€” practical uses

PythonKiddo example
scores = {"Mehak": 98, "Palak": 95, "Rohan": 78, "Arjun": 65}

# Print all names in alphabetical order
for name in sorted(scores):
    print(f"{name}: {scores[name]}")
# Arjun: 65
# Mehak: 98
# Palak: 95
# Rohan: 78

# Count how many students
print(f"Total students: {len(list(scores))}")  # 4

# Get list of names to display in a dropdown
student_names = list(scores)
print(student_names)  # ['Mehak', 'Palak', 'Rohan', 'Arjun']

Checking Dictionary Keys with in and not in

Use the in keyword to check whether a single key is in the dictionary. It's fast โ€” O(1) average time regardless of how big the dictionary is:

PythonPython docs example
tel = {'jack': 4098, 'guido': 4127, 'irv': 4127}

'guido' in tel       # True
'jack' not in tel    # False  โ† jack IS in tel, so not in = False

Kiddo extra โ€” practical patterns

PythonKiddo example
config = {"debug": True, "port": 8080, "host": "localhost"}

# Safe lookup before accessing
if "timeout" in config:
    print(config["timeout"])
else:
    print("No timeout set โ€” using default 30s")

# Check multiple keys
required = ["port", "host", "api_key"]
missing = [key for key in required if key not in config]
print(f"Missing config: {missing}")   # Missing config: ['api_key']

# in checks keys โ€” not values
print(8080 in config)             # False! (checks keys, not values)
print(8080 in config.values())    # True  (checking values explicitly)
Remember: in checks keys by default. To check if a value exists, use value in dict.values(). Key lookups are O(1). Value lookups are O(n) โ€” they scan the whole dictionary.

Python Dictionary Methods Cheat Sheet

Method / ExpressionWhat it doesReturns
d[key]Get value by key โ€” KeyError if missingValue
d[key] = valAdd or update a key-value pairโ€”
del d[key]Delete a key-value pairโ€”
d.get(key, default)Safe access โ€” returns default (None) if key missingValue or default
d.keys()Live view of all keysdict_keys view
d.values()Live view of all valuesdict_values view
d.items()Live view of all (key, value) pairsdict_items view
d.update(other)Merge another dict in โ€” adds new, overwrites existingNone
d.pop(key)Remove key and return its value. KeyError if missingRemoved value
d.popitem()Remove and return the last inserted (key, value) pair(key, value) tuple
d.setdefault(key, val)Return value if key exists โ€” else insert key=val and return valValue
d.copy()Shallow copy โ€” nested dicts still share referencesNew dict
d.clear()Remove all itemsNone
list(d)All keys as a list in insertion orderlist
sorted(d)All keys sorted alphabeticallylist
len(d)Number of key-value pairsint
key in dTrue if key exists (O(1))bool
key not in dTrue if key does NOT existbool

Looping Through a Python Dictionary

Three patterns โ€” each gives you different access:

PythonKiddo example
person = {"name": "Palak", "age": 20, "city": "Delhi"}

# 1 โ€” Keys only (default when you loop a dict)
for key in person:
    print(key)
# name  age  city

# 2 โ€” Values only
for value in person.values():
    print(value)
# Palak  20  Delhi

# 3 โ€” Both at once โ€” USE THIS ONE most of the time
for key, value in person.items():
    print(f"{key}: {value}")
# name: Palak
# age: 20
# city: Delhi

# 4 โ€” In sorted key order (using sorted from the docs)
for key in sorted(person):
    print(f"{key}: {person[key]}")
# age: 20
# city: Delhi
# name: Palak

Dictionary Comprehensions Explained

Dict comprehensions create a dictionary from any key-value expression โ€” in one line. They work exactly like list comprehensions but produce a dict instead.

PythonPython docs example
# From the Python docs ยง5.5 โ€” squares of specific numbers
{x: x**2 for x in (2, 4, 6)}
# {2: 4, 4: 16, 6: 36}

Kiddo extras โ€” more comprehension patterns

PythonKiddo example
# Basic syntax: {key_expr: value_expr for item in iterable}

# 1 โ€” Word lengths
words = ["python", "dict", "comprehension"]
word_len = {word: len(word) for word in words}
# {'python': 6, 'dict': 4, 'comprehension': 13}

# 2 โ€” Uppercase version of each name
names = ["palak", "rohan", "sneha"]
upper = {name: name.upper() for name in names}
# {'palak': 'PALAK', 'rohan': 'ROHAN', 'sneha': 'SNEHA'}

# 3 โ€” With a condition (only pass scores)
scores = {"Palak": 92, "Arjun": 45, "Sneha": 88, "Rohan": 37}
passing = {name: score for name, score in scores.items() if score >= 50}
# {'Palak': 92, 'Sneha': 88}

# 4 โ€” Swap keys and values
original = {"a": 1, "b": 2, "c": 3}
swapped  = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}

# 5 โ€” Squares of 1-5 (range version)
squares = {n: n**2 for n in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
๐Ÿ“˜ From the Python docs

Dict comprehensions can be used to create dictionaries from arbitrary key and value expressions: {x: x**2 for x in (2, 4, 6)} โ†’ {2: 4, 4: 16, 6: 36}.

Nested Dictionaries in Python

Values in a dictionary can themselves be dictionaries. This is how you model structured records โ€” API responses, student data, config files with sections:

PythonKiddo example
students = {
    "Palak": {
        "grade": "A",
        "score": 95,
        "subjects": ["Python", "DSA", "DBMS"]
    },
    "Rohan": {
        "grade": "B",
        "score": 78,
        "subjects": ["Java", "Web Dev"]
    }
}

# Access nested values by chaining keys
print(students["Palak"]["grade"])         # A
print(students["Palak"]["score"])         # 95
print(students["Rohan"]["subjects"][0])   # Java

# Loop through nested dict
for name, info in students.items():
    print(f"{name}: {info['score']}% โ€” Grade {info['grade']}")

# Safe nested access
score = students.get("Ananya", {}).get("score", "not found")
print(score)   # not found  โ† no KeyError even if "Ananya" missing

Common Python Dictionary Mistakes

Using dict[key] without checking โ€” KeyError crash

tel['irv'] crashes if 'irv' isn't in the dict. Use tel.get('irv') or check 'irv' in tel first.

Using a list as a key

d[[1,2]] = "value" throws a TypeError. Lists are mutable, so they can't be keys. Use a tuple instead: d[(1,2)] = "value".

Expecting duplicate keys to keep both values

{'a': 1, 'a': 2} silently becomes {'a': 2}. The second value overwrites the first โ€” no warning, no error.

Modifying a dict while looping over it

Adding or deleting keys during a for key in dict loop raises RuntimeError: dictionary changed size during iteration. Loop over list(dict.items()) if you need to modify while iterating.

Checking values with "in" (it checks keys)

4098 in tel is False โ€” it checks keys, not values. Use 4098 in tel.values() to check values.

Thinking .copy() gives a fully independent copy

dict.copy() is a shallow copy โ€” nested dictionaries inside are still shared references. Use copy.deepcopy(d) for a completely independent clone.

The safe access pattern

When a key might or might not exist: value = d.get('key', 'fallback') โ€” one line, no crash, no if-else needed.

Python Dictionary Interview Questions and Answers

These come up regularly in Python interviews โ€” from beginner screens to technical rounds:

Q1 What is a Python dictionary and how is it different from a list?
A dictionary stores key-value pairs and is indexed by keys. A list stores values in order and is indexed by position (0, 1, 2...). Dict lookup by key is O(1). List lookup by value is O(n). Use a dict when data has a natural label; use a list when order and position matter.
Q2 What types can be used as dictionary keys?
Only immutable types โ€” strings, integers, floats, and tuples (containing only immutable items). Lists and dicts cannot be keys because they can be modified in place, which would break the hash-based lookup mechanism.
Q3 What is the difference between dict.get() and dict[key]?
dict[key] raises a KeyError if the key doesn't exist โ€” this will crash your program. dict.get(key) returns None instead. You can also provide a fallback: dict.get(key, 'default'). Always use .get() when the key might be missing.
Q4 How do you merge two dictionaries in Python?
Three ways: dict1.update(dict2) modifies dict1 in place. {**dict1, **dict2} creates a new merged dict. In Python 3.9+: dict1 | dict2 creates a new merged dict. If keys overlap, the second dict's values win.
Q5 How would you count word frequency in a string using a dictionary?
Loop through the words and use setdefault or get: freq[word] = freq.get(word, 0) + 1. Or use collections.Counter(words.split()) which does the same thing with less code.
Q6 Are Python dictionaries ordered?
Yes โ€” from Python 3.7 onwards, dictionaries maintain insertion order as part of the language spec (not just an implementation detail). In Python 3.6 it was an implementation detail of CPython. Before 3.6, no ordering guarantee existed.
Q7 Write a dict comprehension that creates a dict of numbers and their cubes.
{n: n**3 for n in range(1, 6)} produces {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}. Add a condition with: {n: n**3 for n in range(1, 6) if n % 2 == 0} for even numbers only.

Python Dictionary Project โ€” Word Frequency Counter

A classic dictionary use case โ€” count how many times each word appears in a piece of text. This pattern shows up everywhere: search engines, text analysis, spam filters.

Take a string of text

Split it into words and convert to lowercase so "Python" and "python" count as the same word.

Count frequencies

Use dict.get(word, 0) + 1 to increment each word's count safely โ€” no KeyError if the word hasn't been seen yet.

Sort by frequency

Use sorted(freq.items(), key=lambda x: x[1], reverse=True) to rank most common first.

Print a report

Show the top 5 words and their counts in a clean formatted output.

Add a lookup

Use freq.get(word, 0) to safely look up any word's count โ€” 0 if it wasn't in the text.

Level up: use from collections import Counter; Counter(words) โ€” it does all of step 2 in one line. But writing it manually first is how you understand what Counter is doing under the hood.

Python Dictionary FAQ

A Python dictionary is a collection of key-value pairs where every key is unique. Defined with curly braces {}, it is mutable, ordered (Python 3.7+), and sometimes called an "associative array" or "hash map" in other languages. Keys must be immutable; values can be anything.
Three ways from the Python docs: curly braces {'jack': 4098}, the dict() constructor with keyword args dict(jack=4098), or dict() from a list of tuples dict([('jack', 4098)]). An empty dict is just {}.
dict[key] raises a KeyError if the key doesn't exist. dict.get(key) returns None instead โ€” no crash. You can pass a custom default: dict.get(key, 'fallback'). Use .get() whenever the key might be missing.
A dict comprehension creates a dictionary in one line. From the Python docs: {x: x**2 for x in (2, 4, 6)} produces {2: 4, 4: 16, 6: 36}. Syntax: {key_expr: value_expr for item in iterable}. Add if condition to filter.
Use list(d) for all keys in insertion order. Use sorted(d) for sorted keys. dict.keys() returns a live view object โ€” wrap it in list() if you need an actual list you can index.
Keys must be immutable โ€” strings, numbers, or tuples (containing only immutable items). You can't use lists as keys because lists can be modified in place (append, slice assignment, etc.), which would break the internal hash lookup.
Use the in operator: 'guido' in tel returns True if the key exists. Use not in for the opposite. This checks keys only โ€” use value in d.values() to check values. Key lookups are O(1) (instant).
A nested dictionary has another dictionary as one or more of its values. Example: students = {'Palak': {'score': 95, 'grade': 'A'}}. Access nested values by chaining keys: students['Palak']['score'] returns 95. Use .get() chaining for safe access.
PM
Palak Mishra Backend developer ยท Building beginner-friendly Python docs at Kiddo
More Python topics โ†’

Lists ยท Tuples ยท Sets ยท Functions ยท List Comprehension ยท While Loop