A Python dictionary stores data as key-value pairs, so instead of looking up a value by its position (like a list index), you look it up by a meaningful key. Dictionaries are one of the most used data types in Python — configuration data, JSON responses, counters, and caches are almost always modeled as a dict.
Keys must be unique and hashable (strings, numbers, and tuples work; lists and dicts don't), while values can be absolutely anything, including other dictionaries.
Creating and Accessing a Dictionary
student = {"name": "Asha", "age": 21, "course": "Python"}
print(student["name"]) # direct access
print(student.get("grade")) # .get() returns None instead of raising an error
print(student.get("grade", "N/A")) # .get() with a default value
Output:
Asha
None
N/A
Direct access with student["grade"] would raise a KeyError since that key doesn't exist — .get() is the safer choice whenever a key might be missing.
Updating a Dictionary and Common Methods
student["age"] = 22 # update an existing key
student["grade"] = "A" # add a new key
print(student.keys())
print(student.values())
print(student.items())
for key, value in student.items():
print(f"{key}: {value}")
Output:
dict_keys(['name', 'age', 'course', 'grade'])
dict_values(['Asha', 22, 'Python', 'A'])
dict_items([('name', 'Asha'), ('age', 22), ('course', 'Python'), ('grade', 'A')])
name: Asha
age: 22
course: Python
grade: A
Looping with .items() is the most common way to process a dictionary — it hands you both the key and value together on each pass, which pairs naturally with the for loop you already know.
Dictionary Comprehensions
Just like list comprehensions, dictionaries support a compact comprehension syntax for building a new dict from an iterable:
numbers = [1, 2, 3, 4, 5]
squares = {n: n ** 2 for n in numbers}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Since Python 3.7, dictionaries also preserve insertion order by default, which makes them reliable whenever the order keys were added in actually matters. See our sort a dictionary by value program for a worked example of putting one to practical use.
