Python Dictionary Methods
Python dictionaries are a versatile data structure that store key-value pairs. Python provides a rich set of dictionary methods for adding, updating, removing, and manipulating dictionary data. Here’s an overview of the most commonly used dictionary methods:
1. Adding and Updating Dictionary Items
update([other]): Updates the dictionary with elements from another dictionary or an iterable of key-value pairs. If the key exists, the value is updated; otherwise, the key-value pair is added.person = {"name": "Alice", "age": 25} person.update({"age": 26, "city": "New York"}) # Output: {"name": "Alice", "age": 26, "city": "New York"}setdefault(key, default=None): Returns the value of the key if it exists; otherwise, it inserts the key with the provided default value and returns it.person = {"name": "Alice", "age": 25} person.setdefault("city", "Unknown") # Output: {"name": "Alice", "age": 25, "city": "Unknown"}
2. Accessing Dictionary Items
get(key, default=None): Returns the value for the specified key. If the key is not found, it returns the default value (which isNoneby default).person = {"name": "Alice", "age": 25} age = person.get("age") # Output: 25 city = person.get("city", "Unknown") # Output: "Unknown"keys(): Returns a view object that contains the keys of the dictionary.person = {"name": "Alice", "age": 25} keys = person.keys() # Output: dict_keys(["name", "age"])values(): Returns a view object that contains the values of the dictionary.person = {"name": "Alice", "age": 25} values = person.values() # Output: dict_values(["Alice", 25])items(): Returns a view object that contains the key-value pairs of the dictionary as tuples.person = {"name": "Alice", "age": 25} items = person.items() # Output: dict_items([("name", "Alice"), ("age", 25)])
3. Removing Dictionary Items
pop(key, default=None): Removes the specified key and returns its value. If the key is not found, the default value is returned (or raises aKeyErrorif no default is provided).person = {"name": "Alice", "age": 25} age = person.pop("age") # Output: 25 # After pop: {"name": "Alice"}popitem(): Removes and returns the last key-value pair inserted in the dictionary (since Python 3.7+, dictionaries maintain insertion order). Raises aKeyErrorif the dictionary is empty.person = {"name": "Alice", "age": 25} last_item = person.popitem() # Output: ("age", 25) # After popitem: {"name": "Alice"}clear(): Removes all elements from the dictionary, leaving it empty.person = {"name": "Alice", "age": 25} person.clear() # Output: {}
4. Copying a Dictionary
copy(): Returns a shallow copy of the dictionary.person = {"name": "Alice", "age": 25} person_copy = person.copy() # person_copy: {"name": "Alice", "age": 25}
5. Checking Existence of Keys
inoperator: Used to check if a key exists in the dictionary.person = {"name": "Alice", "age": 25} "age" in person # Output: True
6. Dictionary Comprehensions
Dictionary comprehensions allow you to create dictionaries from an iterable in a concise way.
squares = {x: x**2 for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Example:
Here’s a combination of dictionary methods in action:
# Initializing a dictionary
person = {"name": "Alice", "age": 25}
# Adding or updating items
person.update({"age": 26, "city": "New York"}) # {"name": "Alice", "age": 26, "city": "New York"}
# Accessing values
age = person.get("age") # 26
# Removing an item
city = person.pop("city") # "New York"
# Copying the dictionary
person_copy = person.copy() # {"name": "Alice", "age": 26}
# Checking if a key exists
if "name" in person:
print("Name exists!")
Summary:
- Adding/Updating items:
update(),setdefault() - Accessing items:
get(),keys(),values(),items() - Removing items:
pop(),popitem(),clear() - Copying a dictionary:
copy() - Checking key existence:
inoperator
These dictionary methods provide powerful ways to work with key-value pairs in Python.