Dictionary
A dictionary in Python is an unordered and mutable collection of key-value pairs. Dictionaries are defined using curly braces {}. Each item in a dictionary is a pair of a key and a corresponding value, separated by a colon :. Here’s an example of a dictionary:
my_dict = {
'name': 'John Doe',
'age': 30,
'city': 'New York'
}
In this dictionary, 'name', 'age', and 'city' are keys, and 'John Doe', 30, and 'New York' are their corresponding values.
Accessing Items
You can access the items of a dictionary by referring to its key name:
print(my_dict['name']) # outputs: John Doe
If you try to access a key that does not exist, Python will raise a KeyError. To avoid this, you can use the get method which will return None or a default value if the key does not exist:
print(my_dict.get('address')) # outputs: None
print(my_dict.get('address', 'Unknown')) # outputs: Unknown
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
my_dict['address'] = '123 Main St'
Modifying Items
You can modify the value of a specific item by referring to its key name:
my_dict['city'] = 'Los Angeles'
Removing Items
You can remove items using the pop method or the del keyword:
my_dict.pop('address') # removes the item with key 'address'
del my_dict['age'] # removes the item with key 'age'
Iterating over Items
You can iterate over the keys, values, or key-value pairs in a dictionary:
# Iterating over keys
for key in my_dict:
print(key)
# Iterating over values
for value in my_dict.values():
print(value)
# Iterating over key-value pairs
for key, value in my_dict.items():
print(key, value)
Checking if Key Exists
You can check if a specific key is present in the dictionary:
if 'name' in my_dict:
print('name is a key in my_dict')
Dictionary Comprehension
Dictionary comprehensions provide a concise way to create dictionaries. Here’s an example of creating a dictionary using dictionary comprehension:
squares = {x: x*x for x in range(6)}
print(squares) # outputs: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionaries
You can have dictionaries inside dictionaries, which are known as nested dictionaries:
my_dict = {
'person1': {
'name': 'John Doe',
'age': 30,
},
'person2': {
'name': 'Jane Doe',
'age': 25,
}
}
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, you can use the len() function:
print(len(my_dict)) # outputs: 2
Clearing All Items
You can remove all items in the dictionary using the clear() method:
my_dict.clear()
Dictionaries are a powerful and flexible way to structure data in Python, and they are used extensively in various types of Python development.