Dictionaries in Python
A dictionary is a collection used to store data in key-value pairs.
Instead of accessing data using positions like a list, a dictionary uses a key to access its value.
Example
student = { "name": "Ram", "age": 20, "course": "CSE" }
Here:
"name" → "Ram" "age" → 20 "course" → "CSE"
- Key →
"name" - Value →
"Ram"
1. Creating a Dictionary
Dictionaries are created using curly brackets {}.
student = { "name": "Ram", "age": 20, "marks": 85 }
You can also create an empty dictionary:
student = {}
2. Accessing Dictionary Values
Use the key inside square brackets.
student = { "name": "Ram", "age": 20, "course": "CSE" } print(student["name"]) print(student["age"])
Output:
Ram 20
3. Using get()
You can also use the get() method.
student = { "name": "Ram", "age": 20 } print(student.get("name"))
Output:
Ram
The advantage of get() is that it doesn't normally raise an error when the key doesn't exist.
print(student.get("marks"))
Output:
None
You can provide a default value:
print(student.get("marks", 0))
Output:
0
4. Adding a New Item
You can add a new key-value pair:
student = { "name": "Ram", "age": 20 } student["course"] = "CSE" print(student)
Output:
{'name': 'Ram', 'age': 20, 'course': 'CSE'}
5. Changing a Value
Use the key to change its value.
student = { "name": "Ram", "age": 20 } student["age"] = 21 print(student)
Output:
{'name': 'Ram', 'age': 21}
6. Removing Items
pop()
Removes an item using its key.
student = { "name": "Ram", "age": 20, "course": "CSE" } student.pop("age") print(student)
Output:
{'name': 'Ram', 'course': 'CSE'}
del
del student["course"]
popitem()
Removes the last inserted key-value pair.
student = { "name": "Ram", "age": 20, "course": "CSE" } student.popitem() print(student)
Output:
{'name': 'Ram', 'age': 20}
7. Clear a Dictionary
Use clear() to remove everything.
student = { "name": "Ram", "age": 20 } student.clear() print(student)
Output:
{}
8. Check if a Key Exists
Use in.
student = { "name": "Ram", "age": 20 } print("name" in student)
Output:
True
You can also use:
print("marks" not in student)
Output:
True
9. Dictionary Length
Use len().
student = { "name": "Ram", "age": 20, "course": "CSE" } print(len(student))
Output:
3
10. Getting All Keys
Use keys().
student = { "name": "Ram", "age": 20, "course": "CSE" } print(student.keys())
You can convert it to a list:
print(list(student.keys()))
Output:
['name', 'age', 'course']
11. Getting All Values
Use values().
print(student.values())
Or:
print(list(student.values()))
Output:
['Ram', 20, 'CSE']
12. Getting Keys and Values Together
Use items().
print(student.items())
Output:
dict_items([('name', 'Ram'), ('age', 20), ('course', 'CSE')])
13. Loop Through a Dictionary
Loop through keys
student = { "name": "Ram", "age": 20, "course": "CSE" } for key in student: print(key)
Output:
name age course
Loop through values
for value in student.values(): print(value)
Output:
Ram 20 CSE
Loop through keys and values
for key, value in student.items(): print(key, ":", value)
Output:
name : Ram age : 20 course : CSE
14. Dictionary with Different Data Types
Dictionary values can have different data types.
student = { "name": "Ram", "age": 20, "marks": 85.5, "passed": True }
15. Dictionary with a List
A dictionary value can also be a list.
student = { "name": "Ram", "subjects": ["C", "C++", "Python"] }
Access the list:
print(student["subjects"])
Access an individual subject:
print(student["subjects"][0])
Output:
C
16. Nested Dictionaries
A dictionary can contain another dictionary.
students = { "student1": { "name": "Ram", "age": 20 }, "student2": { "name": "Shyam", "age": 21 } }
Access the data:
print(students["student1"]["name"])
Output:
Ram
17. Copying a Dictionary
Use copy():
student = { "name": "Ram", "age": 20 } new_student = student.copy() print(new_student)
18. Updating a Dictionary
Use update() to add or change multiple values.
student = { "name": "Ram", "age": 20 } student.update({ "age": 21, "course": "CSE" }) print(student)
Output:
{'name': 'Ram', 'age': 21, 'course': 'CSE'}
19. Dictionary Comprehension
Dictionary comprehension provides a short way to create dictionaries.
numbers = {x: x * x for x in range(1, 6)} print(numbers)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
20. Dictionary Keys
Dictionary keys must be hashable objects.
Common examples:
student = { "name": "Ram", 1: "One", 2: "Two", (10, 20): "Coordinates" }
Strings, numbers, and tuples can be used as keys.
A list cannot be used as a dictionary key:
# Invalid data = { [1, 2]: "Example" }
21. Important Dictionary Methods
| Method | Purpose |
|---|---|
get() | Get a value |
keys() | Get all keys |
values() | Get all values |
items() | Get keys and values |
update() | Add/update items |
pop() | Remove an item |
popitem() | Remove last item |
clear() | Remove all items |
copy() | Create a copy |
Dictionary Characteristics
A Python dictionary is:
- Key-value based
- Mutable — values can be changed.
- Ordered — dictionaries preserve insertion order in modern Python.
- Does not allow duplicate keys
- Keys must be hashable
- Values can be of different data types
Duplicate Keys
If you use the same key more than once, the later value replaces the earlier one.
student = { "name": "Ram", "name": "Shyam" } print(student)
Output:
{'name': 'Shyam'}
List vs Dictionary
| List | Dictionary |
|---|---|
| Uses indexes | Uses keys |
[] | {} |
students[0] | student["name"] |
| Ordered collection | Key-value collection |
| Good for sequences | Good for structured data |
Example
List:
student = ["Ram", 20, "CSE"]
Dictionary:
student = { "name": "Ram", "age": 20, "course": "CSE" }
A dictionary is especially useful when you want to store related information with meaningful names, such as student records, user profiles, product details, or configuration data.