-
Hajipur, Bihar, 844101
In Python, dictionaries are one of the most powerful and flexible data structures. They allow you to store data in key-value pairs, which makes them perfect for situations where you need to associate specific information with a unique identifier. Unlike lists and tuples that are indexed by numbers, dictionaries are indexed by keys, which can be strings, numbers, or tuples. This makes dictionaries extremely versatile for a wide range of programming tasks.
In this tutorial, we will explore how to create dictionaries, access and modify their elements, use built-in methods, and handle complex data with nested dictionaries. By the end of this guide, you will understand dictionaries in Python thoroughly.
A dictionary is an unordered collection of items where each item is a pair of a key and a value. Keys are unique and immutable, while values can be of any data type, including numbers, strings, lists, or even other dictionaries.
Example:
student = {
"name": "Emma",
"age": 25,
"courses": ["Python", "Math", "English"],
"is_active": True
}
Here:
"name", "age", "courses", and "is_active" are keys.
"Emma", 25, ["Python", "Math", "English"], and True are values.
Dictionaries are widely used in real-life applications, such as storing user profiles, counting occurrences of words, or mapping configuration settings.
Python provides multiple ways to create dictionaries:
Using Curly Braces {}:
person = {"name": "Emma", "age": 25, "city": "Paris"}
Using the dict() Function:
person = dict(name="Emma", age=25, city="Paris")
Creating an Empty Dictionary:
empty_dict = {}
Using a List of Tuples:
items = dict([("apple", 3), ("banana", 5)])
This flexibility allows you to create dictionaries in different scenarios depending on your data source.
Values in a dictionary are accessed using their keys. Accessing a value with a non-existent key will raise a KeyError, so it’s often better to use the get() method.
student = {"name": "Emma", "age": 25}
# Accessing with key
print(student["name"]) # Output: 'Emma'
# Accessing using get()
print(student.get("name")) # Output: 'Emma'
print(student.get("grade")) # Output: None
The get() method is particularly useful because you can provide a default value if the key does not exist:
print(student.get("grade", "Not Assigned")) # Output: 'Not Assigned'
Dictionaries are mutable, meaning you can add new key-value pairs or update existing ones at any time.
student["grade"] = "A" # Adding a new key-value pair
student["age"] = 26 # Updating an existing value
You can also use the update() method to add or update multiple items at once:
student.update({"city": "London", "is_active": False})
There are several ways to remove elements from a dictionary:
Using pop(key) – removes a key and returns its value:
age = student.pop("age")
Using popitem() – removes the last inserted key-value pair (Python 3.7+):
student.popitem()
Using del – removes a specific key:
del student["grade"]
Using clear() – removes all items, leaving an empty dictionary:
student.clear()
Python dictionaries provide methods to access keys, values, and key-value pairs easily:
keys() – returns all keys:
print(student.keys()) # Output: dict_keys(['name', 'city'])
values() – returns all values:
print(student.values()) # Output: dict_values(['Emma', 'London'])
items() – returns all key-value pairs:
print(student.items()) # Output: dict_items([('name', 'Emma'), ('city', 'London')])
These methods are particularly useful when iterating through a dictionary.
You can iterate over dictionaries in different ways:
Iterate over keys:
for key in student:
print(key, student[key])
Iterate over key-value pairs:
for key, value in student.items():
print(key, value)
Iterate over values only:
for value in student.values():
print(value)
Dictionaries can contain other dictionaries, allowing for complex data structures. This is often used to represent hierarchical data.
students = {
"Emma": {"age": 25, "courses": ["Python", "Math"]},
"Sophia": {"age": 22, "courses": ["English", "History"]}
}
print(students["Emma"]["courses"]) # Output: ['Python', 'Math']
You can create dictionaries dynamically using dictionary comprehension:
squares = {x: x**2 for x in range(1, 6)}
This is useful for generating dictionaries programmatically instead of adding items manually.
Counting Word Occurrences:
words = ["apple", "banana", "apple", "orange"]
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
print(count) # Output: {'apple': 2, 'banana': 1, 'orange': 1}
Merging Dictionaries:
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
Checking Key Existence:
if "name" in student:
print("Key exists")
Iterating Nested Dictionary:
for student, details in students.items():
print(f"{student} is enrolled in {details['courses']}")
Sorting a Dictionary by Keys:
sorted_dict = dict(sorted(squares.items()))
Python dictionaries are unordered, mutable, and highly flexible. They store data in key-value pairs, making it easy to organize and retrieve information efficiently. Dictionaries support operations like adding, updating, removing items, iterating through elements, and handling nested structures. Understanding dictionaries is crucial for any Python programmer because they are widely used in real-world applications, including data storage, APIs, and configuration management.
Create a dictionary student with keys "name", "age", and "courses" and assign appropriate values.
Access and print the value of "name" from the dictionary student.
Add a new key "grade" with value "A" to the dictionary student.
Update the "age" value in the dictionary student to 26.
Remove the key "courses" from the dictionary student using pop().
Check if the key "name" exists in the dictionary student.
Print all keys, all values, and all key-value pairs from the dictionary student.
Create a nested dictionary for two students, where each student has "age" and "courses" as keys.
Use dictionary comprehension to create a dictionary of squares for numbers 1 to 5.
Merge two dictionaries dict1 = {"a": 1, "b": 2} and dict2 = {"b": 3, "c": 4} into a single dictionary and print the result.