Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
A dictionary in Python is an unordered collection of key-value pairs, where each key must be unique. Dictionaries are mutable, which means you can add, remove, or modify items after the dictionary is created. In this tutorial, we'll go through some common operations you can perform on dictionaries.
You can create a dictionary using curly braces {}
and separating keys and values with a colon :
. To create an empty dictionary, use empty curly braces or the dict()
constructor.
# Creating a dictionary with some items person = { "name": "Alice", "age": 30, "occupation": "Engineer" } # Creating an empty dictionary empty_dict1 = {} empty_dict2 = dict()
You can access the value associated with a key using square brackets []
or the get()
method.
person = { "name": "Alice", "age": 30, "occupation": "Engineer" } # Accessing values using square brackets print(person["name"]) # Output: Alice # Accessing values using the get() method print(person.get("age")) # Output: 30
If you use square brackets and the key doesn't exist, you'll get a KeyError
. The get()
method returns None
by default if the key is not found, but you can provide a default value as a second argument.
print(person["city"]) # Raises KeyError print(person.get("city")) # Output: None print(person.get("city", "Unknown")) # Output: Unknown
You can modify the value associated with a key or add a new key-value pair by assigning a value using the key in square brackets.
person = { "name": "Alice", "age": 30, "occupation": "Engineer" } # Modifying a value person["age"] = 31 # Adding a new key-value pair person["city"] = "New York" print(person) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer', 'city': 'New York'}
You can remove a key-value pair from the dictionary using the del
keyword or the pop()
method.
person = { "name": "Alice", "age": 30, "occupation": "Engineer" } # Deleting an item using del del person["age"] # Deleting an item using pop() occupation = person.pop("occupation") print(person) # Output: {'name': 'Alice'}
You can iterate through a dictionary's keys, values, or key-value pairs using the keys()
, values()
, or items()
methods, respectively.
person = { "name": "Alice", "age": 30, "occupation": "Engineer" } # Iterating through keys for key in person.keys(): print(key) # Iterating through values for value in person.values(): print(value) # Iterating through key-value pairs for key, value in person.items(): print(key, value)
Creating dictionaries in Python:
{}
and key-value pairs.# Creating a dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
Accessing and modifying dictionary elements in Python:
# Accessing dictionary elements name = person['name'] # Modifying dictionary elements person['age'] = 26
Dictionary methods and operations in Python:
# Dictionary methods keys = person.keys() values = person.values() items = person.items() # Check if a key is present is_city_present = 'city' in person
Iterating over keys, values, and items in a dictionary:
# Iterating over keys for key in person: print(key) # Iterating over values for value in person.values(): print(value) # Iterating over items (key-value pairs) for key, value in person.items(): print(f"{key}: {value}")
Merging and updating dictionaries in Python:
# Merging dictionaries additional_info = {'gender': 'Female', 'occupation': 'Engineer'} merged_person = {**person, **additional_info} # Updating dictionary person.update({'age': 27, 'city': 'San Francisco'})
Nested dictionaries and dictionary comprehensions in Python:
# Nested dictionaries contacts = {'Alice': {'phone': '123-456-7890', 'email': 'alice@example.com'}, 'Bob': {'phone': '987-654-3210', 'email': 'bob@example.com'}} # Dictionary comprehension squares = {num: num**2 for num in range(1, 6)}
Common use cases for dictionaries in Python:
# Use case: Data storage person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Use case: Mapping fruit_prices = {'apple': 1.0, 'banana': 0.75, 'orange': 1.25} # Use case: Configuration settings config = {'debug_mode': True, 'max_connections': 100}
Error handling and avoiding key errors in Python dictionaries:
get
method or default
argument to handle potential key errors.# Avoiding key errors with get method age = person.get('age', 'N/A') # Avoiding key errors with default argument occupation = person.setdefault('occupation', 'Unknown')