In Python, a dictionary is a collection of key-value pairs. You can think of it like a real-life dictionary, where each word (key) has a definition (value). In Python, you can use various methods to work with dictionaries. Let’s take a look at some of the most commonly used dictionary methods.
What is a Dictionary in Python?
A dictionary in Python is created using curly braces {}
, and each key-value pair is separated by a colon (:
). For example:
# Creating a dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
In the example above:
"name"
,"age"
, and"city"
are keys."Alice"
,30
, and"New York"
are their respective values.
1. clear()
Method
The clear()
method removes all the items from the dictionary, leaving it empty.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
my_dict.clear()
print(my_dict) # Output will be an empty dictionary
Output:
{}
2. copy()
Method
The copy()
method creates a duplicate of the dictionary. This means the original and the copy are separate objects, and changes to one will not affect the other.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
copy_dict = my_dict.copy()
copy_dict["age"] = 31 # Changing the value in the copy
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(copy_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
Output:
Original Dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Copied Dictionary: {'name': 'Alice', 'age': 31, 'city': 'New York'}
3. get()
Method
The get()
method is used to retrieve the value of a given key. If the key does not exist, it returns None
or a default value that you can specify.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("country", "Not Available")) # Output: Not Available
Output:
Alice
Not Available
4. items()
Method
The items()
method returns all the key-value pairs in a dictionary as a list of tuples. Each tuple contains a key and its corresponding value.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Output:
Key: name, Value: Alice
Key: age, Value: 30
Key: city, Value: New York
5. keys()
Method
The keys()
method returns a view object that displays a list of all the keys in the dictionary.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
Output:
dict_keys(['name', 'age', 'city'])
6. pop()
Method
The pop()
method removes a key-value pair from the dictionary by using the specified key and returns the value associated with that key.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
age_value = my_dict.pop("age")
print(f"Removed value: {age_value}") # Output: Removed value: 30
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
Output:
Removed value: 30
{'name': 'Alice', 'city': 'New York'}
7. popitem()
Method
The popitem()
method removes the last key-value pair from the dictionary and returns it as a tuple.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
last_item = my_dict.popitem()
print(f"Removed item: {last_item}") # Output: Removed item: ('city', 'New York')
print(my_dict) # Output: {'name': 'Alice', 'age': 30}
Output:
Removed item: ('city', 'New York')
{'name': 'Alice', 'age': 30}
8. update()
Method
The update()
method allows you to update the dictionary with new key-value pairs or modify existing ones. You can also use it to merge two dictionaries.
Example:
my_dict = {"name": "Alice", "age": 30}
new_info = {"city": "New York", "age": 31}
my_dict.update(new_info)
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
Output:
{'name': 'Alice', 'age': 31, 'city': 'New York'}
9. values()
Method
The values()
method returns a view object that displays a list of all the values in the dictionary.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict.values()) # Output: dict_values(['Alice', 30, 'New York'])
Output:
dict_values(['Alice', 30, 'New York'])
10. setdefault()
Method
The setdefault()
method returns the value of a given key. If the key doesn’t exist, it will add the key to the dictionary with the specified default value.
Example:
my_dict = {"name": "Alice", "age": 30}
# Set default value for 'city' if it doesn't exist
city = my_dict.setdefault("city", "New York")
print(city) # Output: New York
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Output:
New York
{'name': 'Alice', 'age': 30, 'city': 'New York'}