Python Dictionaries – A Complete Guide for Beginners (with Examples and Output)
Dictionaries – A Complete Guide for Beginners (with Examples and Output)
You have already learned about Lists, Tuples, and Sets. Now it is time to learn about Dictionaries — the most powerful and widely used data structure in Python. Unlike lists where you access items by their position, a dictionary lets you access items by a meaningful key. Think of it like a real dictionary — you look up a word (key) to find its meaning (value). In this complete guide, you will learn everything about Python dictionaries with simple examples, clear outputs, and real-life programs.
Table of Contents
- What is a Dictionary in Python?
- How to Create a Dictionary
- Accessing Dictionary Values
- Adding and Updating Items
- Removing Items from a Dictionary
- Important Dictionary Methods
- Looping Through a Dictionary
- Nested Dictionaries
- Dictionary Comprehension
- Checking Keys and Values
- All Data Structures Compared
- Real-Life Projects
- Practice Problems
- FAQ
1. What is a Dictionary in Python?
A dictionary is a collection that stores data as key-value pairs. Instead of accessing items by their index number like in a list, you access them using a meaningful key that you define.
Think of a real English dictionary — you search for a word (the key) and it gives you the meaning (the value). In Python, a dictionary works exactly the same way.
Dictionary properties
Key-value pairs — every item has a key and a value
Ordered — insertion order is preserved (Python 3.7+)
Mutable — you can add, change, or remove items
Keys must be unique — no duplicate keys allowed
When to use a dictionary
When data has labels (name, age, marks)
When you need fast lookup by a name or ID
When storing structured records like a student profile
When building configs, JSON data, or API responses
2. How to Create a Dictionary
A dictionary is created using curly brackets { } with key-value pairs separated by colons :. Each pair is separated by a comma.
# Basic dictionary student = { "name" : "Rohan", "age" : 21, "city" : "Bengaluru", "marks" : 85.5 } print(student) print(type(student)) print(len(student)) # Number of key-value pairs
{'name': 'Rohan', 'age': 21, 'city': 'Bengaluru', 'marks': 85.5}
<class 'dict'>
4Creating a dictionary using dict()
# Using the dict() constructor student = dict(name="Priya", age=20, city="Mumbai") print(student)
{'name': 'Priya', 'age': 20, 'city': 'Mumbai'}Empty dictionary
empty_dict = {}
print(empty_dict)
print(type(empty_dict)){}
<class 'dict'>3. Accessing Dictionary Values
You access values in a dictionary using the key inside square brackets [ ] or using the get() method. Unlike lists, you never use a number index — you use the key name.
student = {"name": "Rohan", "age": 21, "marks": 85}
# Access using key in [ ]
print(student["name"])
print(student["age"])
# Access using get() – safer method
print(student.get("marks"))
print(student.get("grade")) # Key not found → None
print(student.get("grade", "N/A")) # Key not found → "N/A"Rohan 21 85 None N/A
student["grade"] when "grade" does not exist raises a KeyError. Using student.get("grade") safely returns None instead. Always use get() when you are not sure if the key exists.4. Adding and Updating Items
Since dictionaries are mutable, you can add new key-value pairs or update existing ones at any time. Both operations use the same syntax — just assign a value to a key.
Adding a new key-value pair
student = {"name": "Rohan", "age": 21}
print("Before:", student)
# Add new keys
student["city"] = "Bengaluru"
student["marks"] = 90
print("After:", student)Before: {'name': 'Rohan', 'age': 21}
After: {'name': 'Rohan', 'age': 21, 'city': 'Bengaluru', 'marks': 90}Updating an existing value
student = {"name": "Rohan", "age": 21, "marks": 85}
student["marks"] = 92 # Update existing key
print(student){'name': 'Rohan', 'age': 21, 'marks': 92}update() method — add or update multiple keys at once
student = {"name": "Rohan", "age": 21}
student.update({"city": "Bengaluru", "marks": 88, "age": 22})
print(student){'name': 'Rohan', 'age': 22, 'city': 'Bengaluru', 'marks': 88}update() adds new keys if they don't exist, and updates existing keys if they do. It is the cleanest way to merge new data into an existing dictionary.5. Removing Items from a Dictionary
student = {"name": "Rohan", "age": 21, "city": "Bengaluru", "marks": 85}
# pop() – removes by key and returns value
removed = student.pop("city")
print(f"Removed: {removed}")
print(student)
# popitem() – removes and returns the last inserted pair
last = student.popitem()
print(f"Last item removed: {last}")
print(student)
# del – deletes a key directly
del student["age"]
print(student)
# clear() – removes everything
student.clear()
print(student)Removed: Bengaluru
{'name': 'Rohan', 'age': 21, 'marks': 85}
Last item removed: ('marks', 85)
{'name': 'Rohan', 'age': 21}
{'name': 'Rohan'}
{}pop(key) when you know the key. Use popitem() to remove the last inserted item. Use del for a direct quick delete. Use clear() to wipe the entire dictionary.6. Important Dictionary Methods
| Method | What it does | Returns |
|---|---|---|
keys() | Returns all keys | dict_keys view |
values() | Returns all values | dict_values view |
items() | Returns all key-value pairs as tuples | dict_items view |
get(key, default) | Returns value for key, or default if not found | value or None |
update(dict2) | Adds or updates with another dictionary | None |
pop(key) | Removes key and returns its value | value |
popitem() | Removes and returns the last key-value pair | (key, value) tuple |
clear() | Removes all items | None |
copy() | Returns a shallow copy of the dictionary | new dict |
setdefault(key, val) | Returns value if key exists, else inserts key with val | value |
keys(), values(), and items()
student = {"name": "Rohan", "age": 21, "marks": 85}
print(student.keys()) # All keys
print(student.values()) # All values
print(student.items()) # All pairs
# Convert to list for easier use
print(list(student.keys()))dict_keys(['name', 'age', 'marks'])
dict_values(['Rohan', 21, 85])
dict_items([('name', 'Rohan'), ('age', 21), ('marks', 85)])
['name', 'age', 'marks']7. Looping Through a Dictionary
You can use a for loop to iterate through a dictionary. You can loop through keys, values, or both at the same time.
Loop through keys (default)
student = {"name": "Rohan", "age": 21, "marks": 85}
for key in student:
print(key)name age marks
Loop through values
for value in student.values(): print(value)
Rohan 21 85
Loop through key-value pairs using items()
for key, value in student.items(): print(f"{key}: {value}")
name: Rohan age: 21 marks: 85
.items() when you need both the key and value together in a loop. This is the most common way to loop through a dictionary in real Python programs.8. Nested Dictionaries
A nested dictionary is a dictionary inside another dictionary. This is very useful for storing complex, structured data — like a class full of students or a product catalogue.
classroom = {
"student1": {"name": "Rohan", "marks": 85, "grade": "B"},
"student2": {"name": "Priya", "marks": 92, "grade": "A"},
"student3": {"name": "Arjun", "marks": 67, "grade": "C"}
}
# Access nested values
print(classroom["student1"])
print(classroom["student2"]["name"])
print(classroom["student3"]["marks"]){'name': 'Rohan', 'marks': 85, 'grade': 'B'}
Priya
67# Loop through nested dictionary print(f"{'Name':10} {'Marks':6} {'Grade'}") print("-" * 26) for sid, info in classroom.items(): print(f"{info['name']:10} {info['marks']:6} {info['grade']}")
Name Marks Grade -------------------------- Rohan 85 B Priya 92 A Arjun 67 C
9. Dictionary Comprehension
Just like list comprehension, Python allows dictionary comprehension — a short, clean way to create a dictionary from an existing sequence in a single line.
# Create a dict of squares squares = {x: x**2 for x in range(1, 6)} print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}# Create dict from two lists using zip() names = ["Rohan", "Priya", "Arjun"] marks = [85, 92, 67] result = {name: mark for name, mark in zip(names, marks)} print(result)
{'Rohan': 85, 'Priya': 92, 'Arjun': 67}# Filter only passing marks using comprehension all_marks = {"Rohan": 85, "Priya": 32, "Arjun": 67, "Meera": 24} passing = {name: m for name, m in all_marks.items() if m >= 40} print("Passed:", passing)
Passed: {'Rohan': 85, 'Arjun': 67}{key: value for item in iterable if condition}. The if condition part is optional — use it when you need to filter items.10. Checking Keys and Values
Use the in membership operator to check if a key or value exists in a dictionary.
student = {"name": "Rohan", "age": 21, "marks": 85}
# Check keys
print("name" in student) # True
print("grade" in student) # False
print("age" not in student) # False
# Check values
print(85 in student.values()) # True
print("Rohan" in student.values()) # TrueTrue False False True True
11. All Data Structures Compared
You have now learned all four major Python data structures — lists, tuples, sets, and dictionaries. Here is a complete side-by-side comparison.
| Feature | List [ ] | Tuple ( ) | Set { } | Dictionary { } |
|---|---|---|---|---|
| Stores | Values | Values | Unique values | Key-value pairs |
| Ordered? | Yes | Yes | No | Yes (3.7+) |
| Mutable? | Yes | No | Yes | Yes |
| Duplicates? | Yes | Yes | No | Keys: No, Values: Yes |
| Access by | Index | Index | Loop / in | Key |
| Brackets | [ ] | ( ) | { } | { key: value } |
| Best used for | Ordered changeable data | Fixed protected data | Unique values | Labelled structured data |
12. Real-Life Projects
Project 1 – Student Report Card
students = {
"Rohan": [85, 90, 78],
"Priya": [92, 88, 95],
"Arjun": [60, 55, 70]
}
print(f"{'Name':10} {'Average':8} {'Result'}")
print("-" * 30)
for name, marks in students.items():
avg = sum(marks) / len(marks)
result = "Pass" if avg >= 40 else "Fail"
print(f"{name:10} {avg:7.1f} {result}")Name Average Result ------------------------------ Rohan 84.3 Pass Priya 91.7 Pass Arjun 61.7 Pass
Project 2 – Word Frequency Counter
sentence = "python is great python is easy python is fun" words = sentence.split() frequency = {} for word in words: frequency[word] = frequency.get(word, 0) + 1 print("Word Frequencies:") for word, count in frequency.items(): print(f" {word:10}: {count}")
Word Frequencies: python : 3 is : 3 great : 1 easy : 1 fun : 1
Project 3 – Simple Contact Book
contacts = {
"Rohan" : "9876543210",
"Priya" : "9123456789",
"Arjun" : "9988776655"
}
name = input("Search contact: ")
if name in contacts:
print(f"Phone: {contacts[name]}")
else:
print("Contact not found.")Search contact: Priya Phone: 9123456789
13. Practice Problems
Try solving each problem on your own. Use what you have learned in this post and from the Python Lists, Python Loops, and Python Operators posts.
Basic operations
- Create a student dictionary with 4 keys
- Access a value using a key
- Add a new key-value pair
- Update an existing value
- Delete a key using del
Methods practice
- Print all keys of a dictionary
- Print all values of a dictionary
- Loop through items() and print pairs
- Use get() with a default value
- Use setdefault() to add a missing key
Comprehension
- Create a dict of cubes from 1 to 5
- Pair two lists into a dictionary
- Filter only students with marks above 50
- Create a dict of word lengths
- Invert a dictionary (swap keys and values)
Real-life challenges
- Build a word frequency counter
- Create a mini phone book
- Store and display a student report card
- Count each character in a string
- Find the student with the highest marks
- A dictionary stores data as key-value pairs using
{ key: value }syntax - Dictionaries are ordered (Python 3.7+), mutable, and keys must be unique
- Access values using
dict[key]or the saferdict.get(key) - Add or update items by assigning —
dict[key] = value - Use
pop(key)to remove by key,del dict[key]for direct delete keys(),values(), anditems()give views of the dictionary- Use
.items()with a for loop to get both key and value together - Nested dictionaries store structured data like records or profiles
- Dictionary comprehension creates dictionaries in one clean line
- Dictionaries are the foundation of JSON, APIs, and real-world Python programs
Frequently Asked Questions (FAQ)
Q1. What is the difference between a dictionary and a list in Python?
A list stores items accessed by their numeric index (0, 1, 2...). A dictionary stores items accessed by meaningful keys that you define (like "name", "age", "marks"). Use a list when order matters. Use a dictionary when your data has labels.
Q2. Can a Python dictionary have duplicate keys?
No. Dictionary keys must be unique. If you assign the same key twice, the second assignment simply overwrites the first — the old value is replaced. Values, however, can be duplicated — multiple keys can hold the same value.
Q3. What is the difference between dict[key] and dict.get(key)?
dict[key] raises a KeyError if the key does not exist. dict.get(key) returns None if the key is not found — no error is raised. You can also provide a default value: dict.get(key, "default"). Always prefer get() when the key might not exist.
Q4. Can dictionary values be a list or another dictionary?
Yes. Dictionary values can be any data type — strings, numbers, lists, tuples, sets, or even another dictionary. This is what makes dictionaries so powerful for storing complex, structured data.
Q5. Are Python dictionaries ordered?
Yes — from Python 3.7 onwards, dictionaries maintain the insertion order of keys. This means items are always returned in the order you added them. In older versions of Python (3.6 and below), dictionaries were unordered.
Q6. What is dictionary comprehension and when should I use it?
Dictionary comprehension is a compact way to create a dictionary in a single line using the syntax {key: value for item in iterable}. Use it when you need to transform or filter data into a dictionary — it is cleaner and faster than using a traditional for loop to build a dictionary manually.
Found this post helpful? Share it with someone learning Python. Drop your practice solutions in the comments — happy to review them!
"A dictionary is not just a data structure — it is how Python thinks about the real world. Learn it well."
Comments
Post a Comment