A dictionary in Python is a built-in collection used to store data in the form of key-value pairs. Each key is associated with a value, allowing data to be stored and retrieved using meaningful identifiers instead of numerical indexes.
Dictionaries are commonly used when data needs to be organized and accessed based on a specific key. They are useful for representing structured information such as student records, product details, employee information, configuration data, and many other real-world data structures.
Table of Contents
What Is a Dictionary in Python?
A dictionary is a collection that stores data as key-value pairs. A key identifies the data, while its associated value contains the information stored for that key.
Dictionaries are created using curly braces { }, with each key and value separated by a colon.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
print(student)
Output:
{'name': 'Rahul', 'age': 20, 'course': 'Python'}
Here, name, age, and course are keys, while Rahul, 20, and Python are their corresponding values.
Unlike lists and tuples, dictionary values are normally accessed using their associated keys rather than numerical positions.
Why Are Dictionaries Used?
Dictionaries are useful when data has a natural relationship between an identifier and its associated value. Instead of remembering the position of an item, a program can use a meaningful key to access the required information.
- To Store Key-Value Pairs: Dictionaries store data as key-value pairs, where each key is associated with a value.
- To Represent Structured Information: Dictionaries help organize data into meaningful fields, making information easier to read and manage.
- To Access Values Using Meaningful Keys: You can retrieve a value using its key instead of remembering the position of an item.
- To Organize Related Information Together: Dictionaries group related data in one place, making it easier to work with in a program.
- To Store Records and Details: Dictionaries are useful for storing information such as student names, employee details, and product prices.
- To Represent Nested and Hierarchical Data: Dictionaries can contain other dictionaries, allowing you to represent structured data with multiple levels.
Characteristics of Dictionaries
Understanding the characteristics of dictionaries helps explain how they differ from other Python collections. Dictionaries are designed around key-based access rather than positional access.
- Key-Value Based: Data is stored as pairs consisting of a key and a value.
- Keys Are Unique: A dictionary cannot contain two separate entries with the same key.
- Values Can Be Duplicated: Multiple keys can have the same value.
- Mutable: Dictionary contents can be changed after creation.
- Ordered: Dictionaries preserve insertion order in modern Python versions.
- Dynamic: Items can be added or removed as needed.
Creating a Dictionary
Python provides several ways to create dictionaries depending on how the data is available. The most common approach is to write key-value pairs inside curly braces.
1. Creating a Dictionary with Key-Value Pairs
A dictionary can be created by placing key-value pairs inside curly braces. Each key is separated from its value using a colon, while different pairs are separated using commas.
Syntax:
dictionary_name = {key1: value1, key2: value2}
The following example creates a dictionary containing basic information about a student.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
print(student)
Output:
{'name': 'Rahul', 'age': 20, 'course': 'Python'}
2. Creating an Empty Dictionary
An empty dictionary is useful when data will be added later during program execution. It can be created using either curly braces or the dict() constructor.
student = {}
print(student)
print(type(student))
Output:
{}
<class 'dict'>
Unlike an empty set, {} creates an empty dictionary in Python.
3. Creating a Dictionary Using dict()
The dict() constructor provides another way to create a dictionary. It is particularly useful when dictionary data is supplied as keyword arguments or another suitable iterable.
Syntax:
dict(key=value, key=value)
student = dict(name="Rahul", age=20, course="Python") print(student)
Output:
{'name': 'Rahul', 'age': 20, 'course': 'Python'}
4. Creating a Dictionary from a List of Tuples
A dictionary can also be created from an iterable containing pairs of values. Each pair represents one key-value relationship.
data = [
("name", "Rahul"),
("age", 20),
("course", "Python")
]
student = dict(data)
print(student)
Output:
{'name': 'Rahul', 'age': 20, 'course': 'Python'}
Here, the first element of each tuple becomes the key and the second element becomes its value.
Dictionary Keys and Values
A dictionary is built around two main components: keys and values. Understanding their roles is essential because dictionary operations are primarily based on these two components.
1. Dictionary Keys
A key is used to identify a particular value in a dictionary. Keys must be unique within the same dictionary.
student = {
"name": "Rahul",
"age": 20
}
print(student["name"])
Output:
Rahul
2. Dictionary Values
A value is the data associated with a key. Unlike keys, values do not need to be unique.
students = {
"student1": "Python",
"student2": "Python",
"student3": "Java"
}
print(students)
Output:
{'student1': 'Python', 'student2': 'Python', 'student3': 'Java'}
Here, the value Python occurs more than once, which is valid.
3. Key-Value Pairs
Each entry in a dictionary consists of a key and its corresponding value. Together, they form a key-value pair.
product = {
"name": "Laptop",
"price": 50000
}
print(product["name"])
print(product["price"])
Output:
Laptop
50000
Accessing Dictionary Values
Dictionary values can be accessed by providing their corresponding keys. This provides direct access to stored information without relying on numerical positions.
1. Accessing a Value Using a Key
The square bracket notation can be used to retrieve the value associated with a specific key.
Syntax:
dictionary_name[key]
student = {
"name": "Rahul",
"age": 20
}
print(student["name"])
print(student["age"])
Output:
Rahul
20
If the specified key does not exist, square bracket access raises a KeyError.
2. Accessing Nested Dictionary Values
A nested dictionary is a dictionary that contains another dictionary as one or more of its values. Nested dictionaries are useful for representing structured or hierarchical information.
students = {
"student1": {
"name": "Rahul",
"age": 20
},
"student2": {
"name": "Priya",
"age": 21
}
}
print(students["student1"]["name"])
print(students["student2"]["age"])
Output:
Rahul
21
The first key selects a particular student record, while the second key accesses a field inside that record.
Basic Dictionary Operations
Python provides simple syntax for performing common operations on dictionaries. These operations allow programs to check, count, add, update, and remove dictionary data.
1. Checking Whether a Key Exists
The in operator can be used to check whether a key exists in a dictionary.
Syntax:
key in dictionary_name
student = {
"name": "Rahul",
"age": 20
}
print("name" in student)
print("course" in student)
Output:
True
False
Dictionary membership testing checks for the presence of a key, not a value.
2. Finding the Length of a Dictionary
The built-in len() function returns the number of key-value pairs currently stored in a dictionary.
Syntax:
len(dictionary_name)
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
print(len(student))
Output:
3
The result is 3 because the dictionary contains three key-value pairs.
3. Adding Dictionary Items
A new key-value pair can be added by assigning a value to a key that does not already exist.
student = {
"name": "Rahul",
"age": 20
}
student["course"] = "Python"
print(student)
Output:
{'name': 'Rahul', 'age': 20, 'course': 'Python'}
4. Updating Dictionary Items
If a key already exists, assigning a new value to that key updates the existing value.
student = {
"name": "Rahul",
"age": 20
}
student["age"] = 21
print(student)
Output:
{'name': 'Rahul', 'age': 21}
The existing value associated with age is replaced with 21.
5. Removing Dictionary Items: A Basic Overview
Dictionary entries can be removed when they are no longer required. Python provides several statements and methods for removing entries, with the detailed methods covered in the separate Dictionary Methods in Python article.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
del student["age"]
print(student)
Output:
{'name': 'Rahul', 'course': 'Python'}
The del statement removes the specified key-value pair from the dictionary.
Iterating Through a Dictionary
Dictionaries can be traversed using a for loop. Depending on the requirement, a program can iterate through keys, values, or complete key-value pairs.
1. Iterating Through Keys
Iterating directly over a dictionary produces its keys.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
for key in student:
print(key)
Output:
name
age
course
2. Iterating Through Values
The dictionary's values can be accessed by iterating over its values collection. The detailed values() method is covered in the Dictionary Methods article.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
for value in student.values():
print(value)
Output:
Rahul
20
Python
3. Iterating Through Key-Value Pairs
The items() method allows both the key and value to be obtained during iteration. This method is useful when both parts of a dictionary entry are required.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
for key, value in student.items():
print(key, value)
Output:
name Rahul
age 20
course Python
Copying a Dictionary: Basic Concept
Assigning one dictionary variable to another does not create an independent dictionary. Both variables refer to the same dictionary object.
student = {
"name": "Rahul",
"age": 20
}
another_student = student
another_student["age"] = 21
print(student)
Output:
{'name': 'Rahul', 'age': 21}
Changing another_student also changes student because both variables refer to the same dictionary. The copy() method can be used when an independent shallow copy is required and is covered in detail in the Dictionary Methods article.
Converting Dictionary Keys and Values to Other Collections
Dictionary keys and values can be converted into other collection types when required. This is useful when a program needs list-like or tuple-like processing.
The keys() and values() methods provide dictionary views that can be converted using constructors such as list() and tuple().
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
keys_list = list(student.keys())
values_list = list(student.values())
print(keys_list)
print(values_list)
Output:
['name', 'age', 'course']
['Rahul', 20, 'Python']
The resulting collections contain the dictionary's keys and values, respectively, following their dictionary iteration order.
Dictionary vs Other Python Collections
Python provides several built-in collection types, including lists, tuples, sets, and dictionaries. Each collection is designed for different types of data organization and access patterns.
Understanding these differences helps determine which collection is appropriate for a particular problem.
1. Dictionary vs List
A list stores values in an ordered sequence and accesses elements using numerical indexes. A dictionary stores key-value pairs and accesses values using keys.
| Feature | Dictionary | List |
|---|---|---|
| Stores | Key-value pairs | Individual values |
| Access | Using keys | Using indexes |
| Duplicates | Keys must be unique; values can repeat | Allowed |
| Ordering | Preserves insertion order | Ordered |
| Syntax | {"a": 1} | [1, 2, 3] |
| Main use | Key-based data | Ordered collection of values |
2. Dictionary vs Tuple
A tuple stores an ordered collection of values and is immutable. A dictionary stores key-value pairs and can be modified after creation.
| Feature | Dictionary | Tuple |
|---|---|---|
| Stores | Key-value pairs | Individual values |
| Access | Using keys | Using indexes |
| Mutability | Mutable | Immutable |
| Duplicates | Keys must be unique; values can repeat | Allowed |
| Syntax | {"a": 1} | (1, 2, 3) |
| Main use | Structured key-based data | Fixed collection of values |
3. Dictionary vs Set
A set stores unique individual values, while a dictionary stores key-value pairs. Both use curly braces, but the presence of key: value pairs distinguishes a dictionary from a set.
| Feature | Dictionary | Set |
|---|---|---|
| Stores | Key-value pairs | Unique values |
| Access | Using keys | Membership testing or iteration |
| Duplicates | Keys must be unique; values can repeat | Not stored |
| Mutability | Mutable | Mutable |
| Syntax | {"a": 1} | {1, 2, 3} |
| Main use | Key-based structured data | Unique values and set operations |
Practical Examples of Dictionaries
Dictionaries are commonly used to represent structured information because each value can be associated with a meaningful key. The following examples demonstrate several practical situations where dictionaries are useful.
1. Storing Student Information
A dictionary can represent a student's basic information by assigning meaningful keys to each piece of data.
student = {
"name": "Rahul",
"age": 20,
"course": "Python",
"marks": 85
}
print(student["name"])
print(student["marks"])
Output:
Rahul
85
The keys make it clear what each stored value represents.
2. Storing Product Details
Dictionaries can store different types of information about a product in one structured object.
product = {
"name": "Laptop",
"price": 50000,
"stock": 15
}
print(product["name"])
print(product["price"])
print(product["stock"])
Output:
Laptop
50000
15
3. Counting Occurrences
A dictionary can be used to keep track of how many times different values occur. The value associated with each key can represent its current count.
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)
Output:
{'apple': 3, 'banana': 2, 'orange': 1}
Each unique word becomes a key, while its number of occurrences is stored as the corresponding value.
Edge Cases
Dictionaries have several behaviors that can produce unexpected results if their rules are not understood. Paying attention to duplicate keys, missing keys, empty dictionaries, and nested structures helps avoid common problems.
- Duplicate Keys Replace Earlier Values: Dictionary keys must be unique. If the same key appears more than once, the later value replaces the earlier value for that key.
- Accessing a Missing Key Raises a KeyError: Using square brackets to access a key that does not exist raises a KeyError. You can use the get() method to handle missing keys without raising this error.
- Using {} to Create an Empty Dictionary: Writing {} creates an empty dictionary. Unlike sets, dictionaries use curly braces to store key-value pairs.
- Dictionary Membership Checks Keys by Default: Using the in operator with a dictionary checks whether a key exists, not whether a value exists.
- Dictionary Values Can Be Duplicated: Dictionary keys must be unique, but multiple keys can have the same value.
- Modifying a Dictionary During Iteration: Changing a dictionary's size while iterating over it can raise a RuntimeError. To avoid this, iterate over a copy of its items when you need to add or remove entries.
- Accessing Values in Nested Dictionaries: Nested dictionaries require multiple key accesses to retrieve deeply stored values. Using an incorrect key at any level may raise a KeyError when square brackets are used.
Common Mistakes
Most beginner mistakes with dictionaries come from treating them like lists or sets. The following points cover common situations that should be avoided.
- Accessing Values Using an Incorrect Numerical Index: Dictionaries do not use positional indexes like lists. An expression such as dictionary[0] raises a KeyError if 0 is not an existing key.
- Using {} for the Wrong Collection Type: Writing {} creates an empty dictionary, not an empty set. Use set() when you need an empty set.
- Assuming Dictionary Values Must Be Unique: Dictionary keys must be unique, but multiple keys can have the same value.
- Forgetting That Duplicate Keys Overwrite Earlier Values: If the same key is assigned multiple values, the latest assignment replaces the previous value associated with that key.
- Assuming in Checks Dictionary Values: The in operator checks whether a key exists in a dictionary by default. To check for a value, use value in dictionary.values().
- Accessing a Key Without Checking Whether It Exists: Using square brackets with a missing key raises a KeyError. Use the get() method when you want to handle missing keys without raising this error.
- Confusing Assignment with Copying a Dictionary: Assigning one dictionary variable to another does not create a separate dictionary. Both variables refer to the same object, so changes made through either variable affect the same dictionary. Use copy() to create a shallow copy when needed.
Important Rules for Dictionaries
The following rules summarize the fundamental behavior that should be remembered when working with dictionaries in Python.
- Dictionaries Store Key-Value Pairs: A dictionary stores data as key-value pairs, where each key is associated with a value.
- Dictionary Keys Must Be Unique: Each key can appear only once in a dictionary. If a key is repeated, its latest value replaces the earlier value.
- Dictionary Values Can Be Duplicated: Multiple keys can have the same value, even though the keys themselves must be unique.
- Dictionaries Are Mutable: You can add, update, or remove key-value pairs after creating a dictionary.
- Dictionaries Preserve Insertion Order: Python dictionaries preserve the order in which keys are inserted, as a language guarantee since Python 3.7.
- Use Square Brackets to Access Values: You can retrieve a value by placing its key inside square brackets, as in student["name"].
- Missing Keys Raise a KeyError: Accessing a key that does not exist using square brackets raises a KeyError.
- Use in to Check for Keys: The in operator checks whether a key exists in a dictionary by default.
- Use len() to Count Items: The len() function returns the number of key-value pairs in a dictionary.
- Assigning a New Key Adds an Item: Assigning a value to a key that does not exist adds a new key-value pair to the dictionary.
Quick Reference Table
The following table provides a quick overview of the fundamental dictionary concepts and operations discussed in this article.
| Concept | Syntax / Example | Purpose |
|---|---|---|
| Create dictionary | {"a": 1} | Create a dictionary with a key-value pair |
| Empty dictionary | {} | Create an empty dictionary |
| dict() constructor | dict(a=1) | Create a dictionary using the constructor |
| Access value | d["a"] | Retrieve the value associated with a key |
| Membership | "a" in d | Check whether a key exists |
| Length | len(d) | Count key-value pairs |
| Add item | d["a"] = 1 | Add a new key-value pair |
| Update item | d["a"] = 2 | Change an existing value |
| Delete item | del d["a"] | Remove a key-value pair |
| Iterate keys | for key in d | Traverse dictionary keys |
| Iterate values | d.values() | Traverse dictionary values |
| Iterate pairs | d.items() | Traverse keys and values together |
Conclusion
Dictionaries in Python provide an efficient and structured way to store information as key-value pairs. They are particularly useful when data needs to be accessed using meaningful identifiers rather than numerical positions.
Understanding dictionary creation, keys and values, access, membership testing, iteration, nested dictionaries, and basic modifications provides a strong foundation for working with structured data in Python.
Python also provides several built-in dictionary methods for retrieving, modifying, copying, and removing dictionary data. For a detailed explanation of methods such as get(), keys(), values(), items(), update(), pop(), popitem(), setdefault(), and clear(), see the Dictionary Methods in Python article.
Frequently Asked Questions (FAQs)
Here are some common questions beginners may have when working with dictionaries in Python. These questions cover the basic structure, behavior, creation, and usage of dictionaries.
1. What is a dictionary in Python?
A dictionary is a mutable collection that stores data as key-value pairs. Each key is associated with a value, allowing information to be accessed using meaningful keys.
2. How do you create a dictionary in Python?
A dictionary can be created by placing key-value pairs inside curly braces, such as {"name": "Rahul"}. It can also be created using the dict() constructor.
3. Can dictionary values be duplicated?
Yes, dictionary values can be duplicated. However, keys must be unique within a dictionary. If the same key is assigned more than once, its later value replaces the previous value.
4. How do you access a dictionary value?
A value can be accessed using its corresponding key with square bracket notation, such as student["name"]. If the specified key does not exist, this form raises a KeyError.
5. How do you check whether a key exists in a dictionary?
Use the in operator to check whether a key exists. For example, "name" in student returns True when the key is present.
0 Comments