Python Dictionaries: Complete Guide with Examples
A dictionary in Python is a mutable data structure that stores information as key-value pairs.
Instead of accessing values using numeric indexes like a list, dictionaries allow you to retrieve information using meaningful keys.
For example:
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "course": "Python" 5} 6 7print(student)
Output:
1{'name': 'Ankit', 'age': 22, 'course': 'Python'}
Here:
1"name" → key 2"Ankit" → value 3 4"age" → key 522 → value 6 7"course" → key 8"Python" → value
Dictionaries are one of the most commonly used Python data structures because they are ideal for representing structured information.
Why Use Dictionaries?
Suppose you want to store information about a student.
Without a dictionary, you might use separate variables:
1name = "Ankit" 2age = 22 3course = "Python"
With a dictionary, related information can be grouped together:
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "course": "Python" 5}
Now the entire student record is stored in one object.
You can retrieve individual values using their keys:
1print(student["name"]) 2print(student["course"])
Output:
1Ankit 2Python
Dictionaries are commonly used for:
- Student records
- Employee information
- Product catalogs
- Configuration settings
- API responses
- JSON data
- User profiles
- Database records
- Caching
- Counting and grouping data
Important Features of Python Dictionaries
Python dictionaries have several important characteristics:
- Data is stored as key-value pairs.
- Dictionaries are mutable.
- Keys must be unique.
- Values can be duplicated.
- Dictionary keys must be hashable.
- Dictionaries preserve insertion order in modern Python versions.
- Values can contain almost any Python object.
- Dictionaries provide fast average-case lookup by key.
- Dictionaries can contain nested dictionaries.
- Dictionaries support dictionary comprehensions.
For example:
1employee = { 2 "id": 101, 3 "name": "Ankit", 4 "skills": ["Python", "Django", "SQL"], 5 "active": True 6}
A dictionary value can be a list, another dictionary, a number, a string, or another Python object.
Creating a Dictionary
The most common way to create a dictionary is with curly braces {}:
1person = { 2 "name": "Rahul", 3 "age": 25, 4 "city": "Delhi" 5} 6 7print(person)
Output:
1{'name': 'Rahul', 'age': 25, 'city': 'Delhi'}
Each key is followed by a colon : and its corresponding value.
The general structure is:
1dictionary = { 2 key: value, 3 key: value 4}
Creating an Empty Dictionary
You can create an empty dictionary using {}:
1data = {} 2 3print(type(data))
Output:
1<class 'dict'>
You can then add values:
1data["name"] = "Ankit" 2data["age"] = 22 3 4print(data)
Output:
1{'name': 'Ankit', 'age': 22}
Creating a Dictionary with dict()
Python provides the dict() constructor.
1student = dict( 2 name="Ankit", 3 age=22, 4 city="Delhi" 5) 6 7print(student)
Output:
1{'name': 'Ankit', 'age': 22, 'city': 'Delhi'}
This syntax is convenient when the keys are valid Python identifiers.
You can also create a dictionary from key-value pairs:
1student = dict([ 2 ("name", "Ankit"), 3 ("age", 22), 4 ("city", "Delhi") 5]) 6 7print(student)
Dictionary with Different Data Types
A dictionary can contain different types of values.
1data = { 2 "name": "Python", 3 "version": 3.13, 4 "popular": True, 5 "users": 1000000 6} 7 8print(data)
The values have different types:
1name → string 2version → float 3popular → boolean 4users → integer
Accessing Dictionary Values
Use the key inside square brackets to access a value.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "course": "Python" 5} 6 7print(student["name"]) 8print(student["age"]) 9print(student["course"])
Output:
1Ankit 222 3Python
This is different from a list:
1numbers = [10, 20, 30] 2 3print(numbers[0])
Lists use indexes, while dictionaries use keys.
Accessing a Missing Key
If you use square brackets with a key that does not exist, Python raises a KeyError.
1student = { 2 "name": "Ankit" 3} 4 5print(student["age"])
Error:
1KeyError: 'age'
When the key may not exist, get() is usually safer.
1print(student.get("age"))
Output:
1None
You can also provide a default value:
1print(student.get("age", "Not Available"))
Output:
1Not Available
The get() Method
The get() method retrieves a value without raising a KeyError when the key is missing.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6print(student.get("name")) 7print(student.get("city"))
Output:
1Ankit 2None
You can specify a default:
1print(student.get("city", "Unknown"))
Output:
1Unknown
This is particularly useful when working with external data, configuration files, or API responses where a key may be missing.
Adding a New Key
Assign a value to a new key:
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6student["city"] = "Delhi" 7 8print(student)
Output:
1{'name': 'Ankit', 'age': 22, 'city': 'Delhi'}
If the key does not already exist, Python creates it.
Updating an Existing Value
Assign a new value to an existing key:
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6student["age"] = 23 7 8print(student)
Output:
1{'name': 'Ankit', 'age': 23}
The old value is replaced.
Dictionary Keys Must Be Unique
Dictionary keys must be unique.
If the same key appears multiple times, the later value replaces the previous value:
1student = { 2 "name": "Ankit", 3 "name": "Rahul" 4} 5 6print(student)
Output:
1{'name': 'Rahul'}
Therefore, dictionaries cannot store two separate values under the exact same key.
Dictionary Keys
You can retrieve all dictionary keys using the keys() method.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "city": "Delhi" 5} 6 7print(student.keys())
Output:
1dict_keys(['name', 'age', 'city'])
The result is a dictionary view object.
Looping Through Keys
1for key in student: 2 print(key)
Output:
1name 2age 3city
You can also explicitly use keys():
1for key in student.keys(): 2 print(key)
Both approaches work.
Dictionary Values
The values() method returns the dictionary's values.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "city": "Delhi" 5} 6 7print(student.values())
Output:
1dict_values(['Ankit', 22, 'Delhi'])
Looping Through Values
1for value in student.values(): 2 print(value)
Output:
1Ankit 222 3Delhi
Dictionary Items
The items() method returns key-value pairs.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6print(student.items())
Output:
1dict_items([('name', 'Ankit'), ('age', 22)])
Each item is represented as a two-element tuple:
1(key, value)
Looping Through Key-Value Pairs
The most common pattern is:
1for key, value in student.items(): 2 print(key, ":", value)
Output:
1name : Ankit 2age : 22
This pattern is extremely useful when processing dictionaries.
Checking Whether a Key Exists
Use the in operator to check dictionary keys.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6print("name" in student) 7print("city" in student)
Output:
1True 2False
You can also use not in:
1if "city" not in student: 2 print("City is not available")
Output:
1City is not available
Important:
inchecks dictionary keys, not values.
For example:
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6print("name" in student) 7print("Ankit" in student)
Output:
1True 2False
To search values:
1print("Ankit" in student.values())
Output:
1True
Dictionary Length
Use len() to find the number of key-value pairs.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "city": "Delhi" 5} 6 7print(len(student))
Output:
13
The length counts keys, not individual nested elements.
Updating a Dictionary with update()
The update() method adds new key-value pairs or modifies existing ones.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6student.update({ 7 "age": 23, 8 "city": "Delhi" 9}) 10 11print(student)
Output:
1{'name': 'Ankit', 'age': 23, 'city': 'Delhi'}
Here:
agewas updated.citywas added.
You can also use keyword arguments:
1student.update(course="Python") 2 3print(student)
Output:
1{'name': 'Ankit', 'age': 23, 'city': 'Delhi', 'course': 'Python'}
Removing Items with pop()
The pop() method removes a key and returns its value.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6age = student.pop("age") 7 8print("Removed:", age) 9print("Student:", student)
Output:
1Removed: 22 2Student: {'name': 'Ankit'}
If the key does not exist, pop() raises a KeyError unless a default value is provided.
1student = { 2 "name": "Ankit" 3} 4 5city = student.pop("city", "Not Found") 6 7print(city)
Output:
1Not Found
This is useful when removing optional keys safely.
Removing the Last Inserted Item with popitem()
The popitem() method removes and returns the last inserted key-value pair.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "city": "Delhi" 5} 6 7item = student.popitem() 8 9print("Removed:", item) 10print("Remaining:", student)
Output:
1Removed: ('city', 'Delhi') 2Remaining: {'name': 'Ankit', 'age': 22}
Because dictionaries preserve insertion order, popitem() removes the last inserted item.
Removing a Dictionary with del
You can use del to remove a specific key:
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "city": "Delhi" 5} 6 7del student["age"] 8 9print(student)
Output:
1{'name': 'Ankit', 'city': 'Delhi'}
Be careful: deleting a missing key raises KeyError.
1del student["salary"]
Removing All Items with clear()
The clear() method removes every key-value pair.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6student.clear() 7 8print(student)
Output:
1{}
The dictionary still exists; it is simply empty.
Copying a Dictionary
Use copy() to create a shallow copy.
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6student_copy = student.copy() 7 8student_copy["age"] = 23 9 10print("Original:", student) 11print("Copy:", student_copy)
Output:
1Original: {'name': 'Ankit', 'age': 22} 2Copy: {'name': 'Ankit', 'age': 23}
Without copy(), both variables can refer to the same dictionary:
1student = { 2 "name": "Ankit" 3} 4 5student_copy = student 6 7student_copy["name"] = "Rahul" 8 9print(student)
Output:
1{'name': 'Rahul'}
The assignment did not create a new dictionary. Both variables refer to the same object.
Shallow Copy and Nested Dictionaries
copy() creates a shallow copy.
This means the outer dictionary is copied, but nested mutable objects are still shared.
1student = { 2 "name": "Ankit", 3 "skills": ["Python", "SQL"] 4} 5 6student_copy = student.copy() 7 8student_copy["skills"].append("Django") 9 10print(student["skills"])
Output:
1['Python', 'SQL', 'Django']
If you need a completely independent nested structure, Python's copy module provides deepcopy():
1from copy import deepcopy 2 3student = { 4 "name": "Ankit", 5 "skills": ["Python", "SQL"] 6} 7 8student_copy = deepcopy(student) 9 10student_copy["skills"].append("Django") 11 12print(student["skills"]) 13print(student_copy["skills"])
Output:
1['Python', 'SQL'] 2['Python', 'SQL', 'Django']
Nested Dictionaries
A dictionary can contain another dictionary as a value.
1students = { 2 "student1": { 3 "name": "Ankit", 4 "age": 22 5 }, 6 "student2": { 7 "name": "Rahul", 8 "age": 21 9 } 10} 11 12print(students)
You can access nested values using multiple keys:
1print(students["student1"]["name"]) 2print(students["student2"]["age"])
Output:
1Ankit 221
Practical Nested Dictionary Example
Nested dictionaries are useful for structured application data.
1company = { 2 "employee": { 3 "id": 101, 4 "name": "Aman", 5 "department": "IT", 6 "skills": ["Python", "Django", "SQL"] 7 } 8} 9 10print(company["employee"]["department"]) 11print(company["employee"]["skills"])
Output:
1IT 2['Python', 'Django', 'SQL']
Dictionary Containing Lists
Dictionary values can be lists.
1student = { 2 "name": "Ankit", 3 "skills": ["Python", "Django", "SQL"], 4 "marks": [85, 90, 95] 5} 6 7print(student["skills"]) 8print(student["marks"][1])
Output:
1['Python', 'Django', 'SQL'] 290
This combination is common when representing structured application data.
Dictionary Comprehension
A dictionary comprehension provides a concise way to create dictionaries.
The basic syntax is:
1{key: value for item in iterable}
For example:
1squares = { 2 number: number ** 2 3 for number in range(1, 6) 4} 5 6print(squares)
Output:
1{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The expression:
1number: number ** 2
creates each key-value pair.
Dictionary Comprehension with Conditions
You can include an if condition.
1squares = { 2 number: number ** 2 3 for number in range(1, 11) 4 if number % 2 == 0 5} 6 7print(squares)
Output:
1{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Only even numbers are included.
Creating a Dictionary from a List
You can use dictionary comprehension to transform a list.
1names = ["Ankit", "Rahul", "Aman"] 2 3students = { 4 name: len(name) 5 for name in names 6} 7 8print(students)
Output:
1{'Ankit': 5, 'Rahul': 5, 'Aman': 4}
The dictionary maps each name to the length of that name.
Dictionary Comprehension with enumerate()
You can create a dictionary that maps indexes to values:
1languages = ["Python", "Java", "C++"] 2 3language_map = { 4 index: language 5 for index, language in enumerate(languages) 6} 7 8print(language_map)
Output:
1{0: 'Python', 1: 'Java', 2: 'C++'}
Merging Dictionaries
Modern Python provides the | operator for merging dictionaries.
1user = { 2 "name": "Ankit", 3 "age": 22 4} 5 6profile = { 7 "city": "Delhi", 8 "role": "Developer" 9} 10 11combined = user | profile 12 13print(combined)
Output:
1{'name': 'Ankit', 'age': 22, 'city': 'Delhi', 'role': 'Developer'}
If both dictionaries contain the same key, the value from the right-hand dictionary wins:
1first = { 2 "name": "Ankit", 3 "age": 22 4} 5 6second = { 7 "age": 23 8} 9 10result = first | second 11 12print(result)
Output:
1{'name': 'Ankit', 'age': 23}
You can also update an existing dictionary using |=:
1user = { 2 "name": "Ankit", 3 "age": 22 4} 5 6user |= { 7 "age": 23, 8 "city": "Delhi" 9} 10 11print(user)
Dictionary Methods Summary
Python dictionaries provide many useful methods.
| Method | Purpose |
|---|---|
get() | Safely retrieve a value |
keys() | Return dictionary keys |
values() | Return dictionary values |
items() | Return key-value pairs |
update() | Add or update multiple values |
pop() | Remove a specific key and return its value |
popitem() | Remove and return the last inserted item |
clear() | Remove all items |
copy() | Create a shallow copy |
setdefault() | Get a value and optionally insert a default |
The setdefault() Method
setdefault() returns the value for a key.
If the key does not exist, it inserts the key with the specified default value.
1student = { 2 "name": "Ankit" 3} 4 5age = student.setdefault("age", 22) 6 7print(age) 8print(student)
Output:
122 2{'name': 'Ankit', 'age': 22}
If the key already exists, its current value is returned and the value is not replaced:
1student = { 2 "name": "Ankit", 3 "age": 22 4} 5 6age = student.setdefault("age", 30) 7 8print(age) 9print(student)
Output:
122 2{'name': 'Ankit', 'age': 22}
Practical Project: Student Database
A dictionary is a natural choice for representing a student record.
1student = { 2 "roll_no": 101, 3 "name": "Ankit Kushwaha", 4 "course": "Python Programming", 5 "marks": 92 6} 7 8print("Student Information") 9print("-------------------") 10print("Roll No :", student["roll_no"]) 11print("Name :", student["name"]) 12print("Course :", student["course"]) 13print("Marks :", student["marks"])
Output:
1Student Information 2------------------- 3Roll No : 101 4Name : Ankit Kushwaha 5Course : Python Programming 6Marks : 92
Practical Project: Multiple Students
You can use a dictionary where the student ID is the key and another dictionary stores the student's information.
1students = { 2 101: { 3 "name": "Ankit", 4 "marks": 92 5 }, 6 102: { 7 "name": "Rahul", 8 "marks": 88 9 }, 10 103: { 11 "name": "Aman", 12 "marks": 95 13 } 14} 15 16for roll_no, student in students.items(): 17 print( 18 f"Roll No: {roll_no}, " 19 f"Name: {student['name']}, " 20 f"Marks: {student['marks']}" 21 )
Output:
1Roll No: 101, Name: Ankit, Marks: 92 2Roll No: 102, Name: Rahul, Marks: 88 3Roll No: 103, Name: Aman, Marks: 95
This structure is much easier to work with than maintaining separate variables for every student.
Practical Project: Word Frequency Counter
Dictionaries are commonly used for counting occurrences.
1sentence = input("Enter a sentence: ") 2 3words = sentence.lower().split() 4 5word_count = {} 6 7for word in words: 8 word_count[word] = word_count.get(word, 0) + 1 9 10print("Word Frequency:") 11for word, count in word_count.items(): 12 print(f"{word}: {count}")
For example, if the input is:
1python is easy and python is powerful
The result will be similar to:
1python: 2 2is: 2 3easy: 1 4and: 1 5powerful: 1
The get() method makes this pattern simple because a word that does not yet exist starts with a count of 0.
Practical Project: Product Price Lookup
Dictionaries are useful for fast lookups.
1products = { 2 "Laptop": 50000, 3 "Mouse": 500, 4 "Keyboard": 1200 5} 6 7product = input("Enter product name: ") 8 9price = products.get(product) 10 11if price is None: 12 print("Product Not Found") 13else: 14 print(f"{product}: ₹{price}")
This approach avoids a long chain of if and elif statements.
Common Dictionary Errors
Accessing a Missing Key
This raises a KeyError:
1student = { 2 "name": "Ankit" 3} 4 5print(student["age"])
Use get() when the key may not exist:
1print(student.get("age"))
Duplicate Keys
Avoid duplicate keys because the later value replaces the earlier value:
1data = { 2 "name": "Ankit", 3 "name": "Rahul" 4} 5 6print(data)
Output:
1{'name': 'Rahul'}
Using a Mutable Object as a Key
Dictionary keys must be hashable.
This is invalid:
1data = { 2 [1, 2]: "Python" 3}
Error:
1TypeError: unhashable type: 'list'
A tuple containing hashable elements can be used as a key:
1locations = { 2 (28.6139, 77.2090): "Delhi" 3} 4 5print(locations[(28.6139, 77.2090)])
Output:
1Delhi
Dictionary Keys vs Values
It is important to understand that dictionary keys and values have different requirements.
Keys:
- Must be unique.
- Must be hashable.
Values:
- Do not need to be unique.
- Can be mutable.
- Can contain lists, dictionaries, sets, or custom objects.
For example:
1data = { 2 "skills": ["Python", "Django"], 3 "projects": ["Website", "API"], 4 "active": True 5}
The lists are valid because they are values, not keys.
Dictionary vs List vs Tuple vs Set
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Syntax | [] | () | {} | {key: value} |
| Ordered | Yes | Yes | No | Yes, insertion order |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Yes | Yes | No | Keys: No |
| Indexing | Yes | Yes | No | No |
| Key-value data | No | No | No | Yes |
| Main use | Changeable sequence | Fixed sequence | Unique values | Structured lookup |
A simple rule for choosing a collection:
1Need an ordered, changeable collection? 2→ List 3 4Need an ordered, immutable collection? 5→ Tuple 6 7Need unique values and set operations? 8→ Set 9 10Need key-value relationships? 11→ Dictionary
Practice Exercises
Exercise 1: Create a Student Dictionary
Create a dictionary containing:
- Name
- Age
- Course
- Marks
Then print each value.
1student = { 2 "name": "Ankit", 3 "age": 22, 4 "course": "Python", 5 "marks": 90 6} 7 8print(student["name"]) 9print(student["age"]) 10print(student["course"]) 11print(student["marks"])
Exercise 2: Update Student Marks
Change the student's marks from 80 to 95.
1student = { 2 "name": "Ankit", 3 "marks": 80 4} 5 6student["marks"] = 95 7 8print(student)
Expected output:
1{'name': 'Ankit', 'marks': 95}
Exercise 3: Product Lookup
Create a product dictionary and retrieve a product price using get().
1products = { 2 "Laptop": 50000, 3 "Mouse": 500, 4 "Keyboard": 1200 5} 6 7product = input("Enter product name: ") 8 9print(products.get(product, "Product Not Found"))
Exercise 4: Count Words
Write a program that counts how many times each word occurs in a sentence.
1sentence = input("Enter a sentence: ") 2 3word_count = {} 4 5for word in sentence.lower().split(): 6 word_count[word] = word_count.get(word, 0) + 1 7 8print(word_count)
Exercise 5: Find Students with High Marks
Create a dictionary of students and print students whose marks are at least 90.
1students = { 2 "Ankit": 92, 3 "Rahul": 88, 4 "Aman": 95, 5 "Riya": 84 6} 7 8for name, marks in students.items(): 9 if marks >= 90: 10 print(name, marks)
Expected output:
1Ankit 92 2Aman 95
Exercise 6: Dictionary Comprehension
Create a dictionary containing numbers from 1 to 5 and their squares.
1squares = { 2 number: number ** 2 3 for number in range(1, 6) 4} 5 6print(squares)
Expected output:
1{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Key Takeaways
A Python dictionary stores data using key-value pairs and is one of the most important data structures in Python.
Remember these concepts:
- Dictionaries use
{key: value}syntax. - Dictionary keys must be unique and hashable.
- Dictionary values can contain different data types.
- Dictionaries are mutable.
- Modern Python dictionaries preserve insertion order.
- Use
dictionary[key]when the key is expected to exist. - Use
get()when a key may be missing. - Use
keys()to access keys. - Use
values()to access values. - Use
items()to iterate over key-value pairs. - Use
update()to add or modify multiple values. - Use
pop()to remove a specific key. - Use
popitem()to remove the last inserted item. - Use
clear()to empty a dictionary. - Use
copy()for a shallow copy. - Use
setdefault()to retrieve or initialize a key. - Dictionaries can contain nested dictionaries and lists.
- Dictionary comprehensions provide a concise way to create dictionaries.
- The
|operator can merge dictionaries. - Dictionaries are widely used for structured data, lookups, counting, configuration, APIs, and JSON-like data.
Once you understand dictionaries, you have a strong foundation for working with JSON, APIs, databases, configuration files, web development, data processing, and Python applications.