Introduction to Dictionaries
Dictionaries are a fundamental data structure in Python, providing a way to store collections of data in key-value pairs. They are incredibly versatile and efficient for retrieving information when you know a specific identifier (the key). In many other programming languages, this data structure is known as a hash map or associative array.
What are Key-Value Pairs?
Imagine you have a list of players and their corresponding jersey numbers. You can easily look up a player’s number if you know their name. This is the basic idea behind key-value pairs.
- Key: The unique identifier (e.g., player’s name, a product ID, a street number). Keys must be immutable – meaning their value cannot be changed after creation. Common key types include strings, numbers, and tuples.
- Value: The data associated with the key (e.g., jersey number, product details, player’s name). Values can be of any data type – strings, numbers, lists, even other dictionaries!
Creating Dictionaries
There are several ways to create dictionaries in Python:
1. Using Curly Braces {}
:
This is the most common and straightforward method. You define the dictionary with curly braces, and inside, you list the key-value pairs separated by colons :
.
player_info = {
"Sachin": "Batsman",
"Dravid": "Batsman",
"Sehwag": "Batsman"
}
print(player_info) # Output: {'Sachin': 'Batsman', 'Dravid': 'Batsman', 'Sehwag': 'Batsman'}
2. Using the dict()
Constructor:
The dict()
constructor can be used in a couple of ways:
-
From keyword arguments: This is suitable when your keys are valid Python identifiers (variable names).
player_info = dict(Sachin="Batsman", Dravid="Batsman", Sehwag="Batsman") print(player_info) # Output: {'Sachin': 'Batsman', 'Dravid': 'Batsman', 'Sehwag': 'Batsman'}
-
From a list of tuples: Each tuple contains a key-value pair.
player_list = [("Sachin", "Batsman"), ("Dravid", "Batsman"), ("Sehwag", "Batsman")] player_info = dict(player_list) print(player_info) # Output: {'Sachin': 'Batsman', 'Dravid': 'Batsman', 'Sehwag': 'Batsman'}
3. Empty Dictionary:
You can create an empty dictionary and populate it later.
player_info = {}
player_info["Sachin"] = "Batsman"
player_info["Dravid"] = "Batsman"
print(player_info)
Accessing Values
You access values in a dictionary using their corresponding keys within square brackets []
.
player_info = {"Sachin": "Batsman", "Dravid": "Batsman", "Sehwag": "Batsman"}
sachin_role = player_info["Sachin"]
print(sachin_role) # Output: Batsman
Important: If you try to access a key that doesn’t exist, a KeyError
will be raised.
Safe Access with get()
The get()
method provides a safer way to access values. It returns the value associated with the key if it exists, and a default value (which you can specify) if the key doesn’t exist.
player_info = {"Sachin": "Batsman", "Dravid": "Batsman"}
kohli_role = player_info.get("Kohli", "Unknown") # Returns "Unknown" if "Kohli" is not a key
print(kohli_role) # Output: Unknown
sachin_role = player_info.get("Sachin")
print(sachin_role) # Output: Batsman
Modifying and Deleting Entries
-
Adding/Updating: You can add new key-value pairs or update existing values using the assignment operator.
player_info = {"Sachin": "Batsman"} player_info["Dravid"] = "Batsman" # Adds Dravid player_info["Sachin"] = "Captain" # Updates Sachin's role print(player_info)
-
Deleting: Use the
del
keyword or thepop()
method to remove entries.player_info = {"Sachin": "Batsman", "Dravid": "Batsman"} del player_info["Dravid"] # Deletes Dravid print(player_info) sachin_role = player_info.pop("Sachin") #Deletes and returns Sachin's role. print(sachin_role)
Checking for Key Existence
Use the in
operator to check if a key exists in the dictionary.
player_info = {"Sachin": "Batsman", "Dravid": "Batsman"}
if "Sachin" in player_info:
print("Sachin is in the dictionary")
if "Kohli" not in player_info:
print("Kohli is not in the dictionary")
Dictionary Iteration
You can iterate through the keys, values, or key-value pairs of a dictionary.
player_info = {"Sachin": "Batsman", "Dravid": "Batsman", "Sehwag": "Batsman"}
# Iterate through keys
for key in player_info:
print(key)
# Iterate through values
for value in player_info.values():
print(value)
# Iterate through key-value pairs
for key, value in player_info.items():
print(f"Key: {key}, Value: {value}")
Use Cases
Dictionaries are incredibly useful in various scenarios:
- Storing configurations: Representing application settings.
- Counting occurrences: Tracking the frequency of items in a list.
- Implementing caches: Storing frequently accessed data for faster retrieval.
- Representing relationships: Modeling data with key-value associations.