In Python, a dictionary is an unordered collection of key-value pairs. Dictionaries are one of the most versatile data structures in Python and are used to store and retrieve data efficiently. This article explains the concept of dictionaries, their properties, and how to use them with examples.
A dictionary in Python is a collection of items stored as key-value pairs. Each key in a dictionary is unique, and it maps to a specific value. The key-value structure allows you to quickly retrieve values based on their corresponding keys.
# Defining a dictionary person = { "name": "John", "age": 30, "profession": "Engineer" } print(person) # Outputs: {'name': 'John', 'age': 30, 'profession': 'Engineer'}
You can access the values in a dictionary by using their corresponding keys. If the key does not exist, Python raises a KeyError.
# Accessing values using keys person = {"name": "John", "age": 30, "profession": "Engineer"} print(person["name"]) # Outputs: John print(person["age"]) # Outputs: 30
# Handling a KeyError person = {"name": "John", "age": 30} try: print(person["address"]) # This will raise a KeyError except KeyError as e: print(f"Error: {e}") # Outputs: Error: 'address'
You can add new key-value pairs to a dictionary or modify the value of an existing key by simply assigning a new value to the key.
# Adding a new key-value pair person = {"name": "John", "age": 30} person["profession"] = "Engineer" # Adds the new key 'profession' with value 'Engineer' print(person) # Outputs: {'name': 'John', 'age': 30, 'profession': 'Engineer'} # Modifying an existing key-value pair person["age"] = 31 # Updates the value of the 'age' key print(person) # Outputs: {'name': 'John', 'age': 31, 'profession': 'Engineer'}
To remove a key-value pair from a dictionary, you can use the del
statement or the pop()
method.
del
to Remove a Key-Value Pair# Using del to remove a key-value pair person = {"name": "John", "age": 30, "profession": "Engineer"} del person["age"] # Removes the 'age' key-value pair print(person) # Outputs: {'name': 'John', 'profession': 'Engineer'}
pop()
to Remove a Key-Value Pair# Using pop to remove a key-value pair and return the value person = {"name": "John", "age": 30, "profession": "Engineer"} age = person.pop("age") # Removes 'age' and returns its value print(age) # Outputs: 30 print(person) # Outputs: {'name': 'John', 'profession': 'Engineer'}
You can loop through a dictionary to access its keys, values, or both.
# Looping through keys and values person = {"name": "John", "age": 30, "profession": "Engineer"} for key, value in person.items(): print(f"{key}: {value}") # Outputs: # name: John # age: 30 # profession: Engineer
Python dictionaries come with various built-in methods for performing common tasks.
get()
Method# Using the get() method person = {"name": "John", "age": 30} print(person.get("name")) # Outputs: John print(person.get("address", "Not Available")) # Outputs: Not Available (default value if key does not exist)
keys()
, values()
, and items()
# Using keys(), values(), and items() methods person = {"name": "John", "age": 30, "profession": "Engineer"} print(person.keys()) # Outputs: dict_keys(['name', 'age', 'profession']) print(person.values()) # Outputs: dict_values(['John', 30, 'Engineer']) print(person.items()) # Outputs: dict_items([('name', 'John'), ('age', 30), ('profession', 'Engineer')])
Dictionaries are an essential data structure in Python that allow for efficient storage and retrieval of data in key-value pairs. Understanding how to use and manipulate dictionaries is crucial for handling complex data and solving real-world problems in Python.