
Python Basics: Dictionaries
Python Basics: Dictionaries
In Python, a dictionary is a data structure that stores a collection of objects. Unlike lists and tuples, which store objects in a sequence, dictionaries hold information as key-value pairs. Each key is associated with a single value, creating a unique relationship between the two.
What Is a Dictionary and How Is It Structured?
A dictionary consists of key-value pairs, where each key is unique and is used to access its corresponding value. The keys within a dictionary must be of an immutable data type, such as strings, numbers, or tuples. The values in a dictionary can be of any data type, including lists or other dictionaries.
# Creating a dictionary
employee = {
"name": "John Doe",
"age": 30,
"department": "HR"
}How Dictionaries Differ From Other Data Structures
Dictionaries differ from other data structures like lists and tuples in that they use keys to access values, rather than numerical indices. This allows for more descriptive and meaningful access to the data within the dictionary.
# Accessing dictionary values using keys
print(employee["name"]) # Output: John Doe
print(employee["age"]) # Output: 30Defining and Using Dictionaries in Your Code
Creating a dictionary in Python is straightforward. The dict() constructor or the use of curly braces {} can be used to define a dictionary. Values can be assigned, accessed, and updated using the associated keys.
# Using the dict() constructor
person = dict(name="Alice", age=25, department="IT")
# Accessing and updating dictionary values
print(person["age"]) # Output: 25
person["age"] = 26
print(person["age"]) # Output: 26Conclusion
Dictionaries in Python provide a flexible and efficient way to store and access data through key-value pairs. Understanding how to define, access, and manipulate dictionaries is essential for working with complex data structures in Python.
