Dictionary Methods
Core Dictionary Methods
Dictionaries provide several built-in methods for creating, accessing, modifying, and removing data. The table below summarizes the most commonly used ones.
| Method | Description | Example |
|---|---|---|
| clear() | Removes all items from the dictionary | d.clear() |
| copy() | Returns a shallow copy of the dictionary | d2 = d.copy() |
| fromkeys(seq[, value]) | Creates a new dictionary with keys from seq and values set to value | dict.fromkeys(['a', 'b'], 0) |
| get(key[, default]) | Returns the value for key, or default if key doesn't exist | d.get('key', 'default') |
| items() | Returns a view object of key-value pairs | for k, v in d.items() |
| keys() | Returns a view object of keys | for k in d.keys() |
| pop(key[, default]) | Removes and returns value for key, or default if key doesn't exist | d.pop('key') |
| popitem() | Removes and returns the last inserted key-value pair (FIFO in Python 3.7+) | d.popitem() |
| setdefault(key[, default]) | Returns value if key exists, else inserts key with default value | d.setdefault('key', 'value') |
| update([other]) | Updates dictionary with key-value pairs from other | d.update({'key': 'value'}) |
| values() | Returns a view object of values | for v in d.values() |
Method Examples
Here are examples of some commonly used methods in action.
Example
# Dictionary method examples
d = {"a": 1, "b": 2, "c": 3}
# fromkeys
new_dict = dict.fromkeys(["x", "y", "z"], 0)
print("fromkeys:", new_dict)
# get
value = d.get("b", "Not found")
print("get b:", value)
# setdefault
result = d.setdefault("d", 4)
print("setdefault d:", result)
print("Dictionary after setdefault:", d)
# popitem
item = d.popitem()
print("popitem:", item)
print("Dictionary after popitem:", d)Output
fromkeys: {'x': 0, 'y': 0, 'z': 0}
get b: 2
setdefault d: 4
Dictionary after setdefault: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
popitem: ('d', 4)
Dictionary after popitem: {'a': 1, 'b': 2, 'c': 3}View Objects
The keys(), values(), and items() methods return dynamic view objects. Any changes made to the dictionary are immediately reflected in these views.
Example
# View objects example
d = {"a": 1, "b": 2, "c": 3}
# Create view objects
keys_view = d.keys()
values_view = d.values()
items_view = d.items()
print("Original views:")
print("Keys:", list(keys_view))
print("Values:", list(values_view))
print("Items:", list(items_view))
# Modify dictionary
d["d"] = 4
d["a"] = 10
print("\nViews after modification:")
print("Keys:", list(keys_view))
print("Values:", list(values_view))
print("Items:", list(items_view))Output
Original views:
Keys: ['a', 'b', 'c']
Values: [1, 2, 3]
Items: [('a', 1), ('b', 2), ('c', 3)]
Views after modification:
Keys: ['a', 'b', 'c', 'd']
Values: [10, 2, 3, 4]
Items: [('a', 10), ('b', 2), ('c', 3), ('d', 4)]