Understanding Python Dictionaries
Dictionaries in Python are a powerful data structure that stores data as key-value pairs. They offer an efficient way to manage and access data using unique keys.
What is a Dictionary?
A dictionary is a mutable, ordered* collection that does not permit duplicate keys. As of Python 3.7, dictionaries maintain the order of insertion. In versions prior to Python 3.7, dictionaries are unordered and do not guarantee the order of items.
Dictionaries are defined using curly brackets {}
and consist of key-value pairs. Here’s an example using student information:
student_info = {
"name": "Emily",
"grade": "A",
"year": 2023
}
print(student_info)
Accessing Dictionary Items
You can access dictionary items using their keys. For instance, to get the value associated with the key "name"
:
student_info = {
"name": "Emily",
"grade": "A",
"year": 2023
}
print(student_info["name"])
Ordered vs. Unordered Dictionaries
From Python 3.7 onwards, dictionaries are ordered, meaning items are kept in the order they are inserted. Prior to Python 3.7, dictionaries do not maintain order. You cannot access dictionary items by index, but you can access them by using their keys.
Modifying Dictionaries
Dictionaries are mutable, allowing you to add, change, or remove items after their creation. Duplicate keys are not allowed; if you use a key more than once, the last value specified for that key will overwrite any previous values. For example:
student_info = {
"name": "Emily",
"grade": "A",
"year": 2023,
"year": 2024
}
print(student_info)
Dictionary Length
To determine the number of items in a dictionary, you can use the len()
function:
print(len(student_info))
Dictionary Values – Data Types
Values in a dictionary can be of any data type, such as strings, integers, booleans, or lists. Here’s an example with a book’s details:
book_info = {
"title": "1984",
"author": "George Orwell",
"published_year": 1949,
"genres": ["dystopian", "political fiction", "social science fiction"]
}
To find out the data type of a dictionary, use the type()
function:
print(type(book_info))
Creating Dictionaries with the dict()
Constructor
Another way to create dictionaries is by using the dict()
constructor. Here’s an example:
employee_info = dict(name="John Doe", position="Developer", department="IT")
print(employee_info)
Python Collections
Python offers several collection types, each with unique characteristics:
- List: Ordered and mutable; allows duplicate elements.
- Tuple: Ordered and immutable; allows duplicate elements.
- Set: Unordered and mutable; no duplicate elements.
- Dictionary: Ordered* and mutable; no duplicate keys.
Choosing the appropriate collection type based on your specific needs can enhance data handling, performance, and security.
*From Python 3.7 onwards, dictionaries are ordered. Older versions do not guarantee order.