Python Dictionary Documentation Explained (Python Docs 5.5) โ dict(), get(), Comprehensions & Examples
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.
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:
# 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
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:
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
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
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.
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()
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:
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']
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
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:
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
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)
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 / Expression | What it does | Returns |
|---|---|---|
d[key] | Get value by key โ KeyError if missing | Value |
d[key] = val | Add 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 missing | Value or default |
d.keys() | Live view of all keys | dict_keys view |
d.values() | Live view of all values | dict_values view |
d.items() | Live view of all (key, value) pairs | dict_items view |
d.update(other) | Merge another dict in โ adds new, overwrites existing | None |
d.pop(key) | Remove key and return its value. KeyError if missing | Removed 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 val | Value |
d.copy() | Shallow copy โ nested dicts still share references | New dict |
d.clear() | Remove all items | None |
list(d) | All keys as a list in insertion order | list |
sorted(d) | All keys sorted alphabetically | list |
len(d) | Number of key-value pairs | int |
key in d | True if key exists (O(1)) | bool |
key not in d | True if key does NOT exist | bool |
Looping Through a Python Dictionary
Three patterns โ each gives you different access:
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.
# 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
# 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}
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:
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
tel['irv'] crashes if 'irv' isn't in the dict. Use tel.get('irv') or check 'irv' in tel first.
d[[1,2]] = "value" throws a TypeError. Lists are mutable, so they can't be keys. Use a tuple instead: d[(1,2)] = "value".
{'a': 1, 'a': 2} silently becomes {'a': 2}. The second value overwrites the first โ no warning, no error.
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.
4098 in tel is False โ it checks keys, not values. Use 4098 in tel.values() to check values.
dict.copy() is a shallow copy โ nested dictionaries inside are still shared references. Use copy.deepcopy(d) for a completely independent clone.
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:
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.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.setdefault or get: freq[word] = freq.get(word, 0) + 1. Or use collections.Counter(words.split()) which does the same thing with less code.{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.
Split it into words and convert to lowercase so "Python" and "python" count as the same word.
Use dict.get(word, 0) + 1 to increment each word's count safely โ no KeyError if the word hasn't been seen yet.
Use sorted(freq.items(), key=lambda x: x[1], reverse=True) to rank most common first.
Show the top 5 words and their counts in a clean formatted output.
Use freq.get(word, 0) to safely look up any word's count โ 0 if it wasn't in the text.
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
{}, 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.{'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.{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.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.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).students = {'Palak': {'score': 95, 'grade': 'A'}}. Access nested values by chaining keys: students['Palak']['score'] returns 95. Use .get() chaining for safe access.