Dictionaries are versatile data structures in Python, offering key-value pair storage and fast lookup times. Understanding dictionary operations is crucial for efficient data manipulation.
To create a dictionary, use curly braces {}
or the dict()
constructor:
# Using curly braces
my_dict = {'name': 'John', 'age': 30}
# Using dict() constructor
another_dict = dict(city='New York', country='USA')
Access values using square bracket notation or the get()
method:
print(my_dict['name']) # Output: John
print(my_dict.get('age')) # Output: 30
print(my_dict.get('gender', 'Not specified')) # Output: Not specified
Add or update key-value pairs easily:
my_dict['job'] = 'Engineer' # Add new key-value pair
my_dict['age'] = 31 # Update existing value
Python provides several useful methods for dictionary operations:
keys()
: Returns a list of all keysvalues()
: Returns a list of all valuesitems()
: Returns a list of key-value tuplespop(key)
: Removes and returns the value for the specified keyclear()
: Removes all items from the dictionaryIterate through dictionaries using loops:
for key in my_dict:
print(f"{key}: {my_dict[key]}")
for key, value in my_dict.items():
print(f"{key}: {value}")
Create dictionaries concisely using comprehensions:
squares = {x: x**2 for x in range(5)}
# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
In Python 3.5+, use the **
operator to merge dictionaries:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged = {**dict1, **dict2}
# Result: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
get()
method to avoid KeyError exceptionsMastering dictionary operations enhances your ability to work with complex data structures in Python. They are particularly useful when dealing with JSON data or implementing caching mechanisms.
To further expand your Python knowledge, explore these related topics: