Essential Python Dictionary Methods

Python Logo

Dictionaries are a fundamental data structure in Python. Here are some of the most common and useful methods for working with them.

user = {"name": "Alice", "age": 25, "city": "New York"}

`.keys()`

Returns a view object that displays a list of all the keys in the dictionary.

print(user.keys()) # dict_keys(['name', 'age', 'city'])

`.values()`

Returns a view object that displays a list of all the values in the dictionary.

print(user.values()) # dict_values(['Alice', 25, 'New York'])

`.items()`

Returns a view object that displays a list of key-value tuple pairs. This is very useful for iterating over a dictionary.

for key, value in user.items():
    print(f"{key}: {value}")

`.get(key, default)`

Returns the value for a key, but if the key is not found, it returns a default value (which is `None` if not specified) instead of raising a `KeyError`.

print(user.get('country', 'USA')) # USA

`.pop(key)`

Removes the specified key and returns the corresponding value. If the key is not found, it raises a `KeyError`.

city = user.pop('city')
print(f"Popped city: {city}")
print(user) # {'name': 'Alice', 'age': 25}

`.update(other_dict)`

Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs. Existing keys are overwritten.

user.update({'age': 26, 'email': 'alice@example.com'})
print(user) # {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}

Comments