Python Dictionary Methods with Examples
1. dict.clear()
Removes all elements from the dictionary.
Example:
d = {'a': 1, 'b': 2}
d.clear()
print(d) # Output: {}
2. dict.copy()
Returns a shallow copy of the dictionary.
Example:
d1 = {'x': 10, 'y': 20}
d2 = d1.copy()
print(d2) # Output: {'x': 10, 'y': 20}
3. dict.fromkeys(seq, value)
Creates a dictionary from a sequence of keys and sets all values to the given value.
Example:
keys = ['a', 'b', 'c']
new_dict = dict.fromkeys(keys, 0)
print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
4. dict.get(key, default=None)
Returns the value for the key if it exists, else returns the default.
Example:
d = {'a': 1}
print(d.get('a')) # Output: 1
print(d.get('b', 0)) # Output: 0
5. dict.has_key(key)
Deprecated in Python 3. Use 'key in dict' instead.
Example:
d = {'a': 1}
print('a' in d) # Output: True
6. dict.items()
Returns a view of the dictionary's (key, value) pairs.
Example:
d = {'a': 1, 'b': 2}
print(d.items()) # Output: dict_items([('a', 1), ('b', 2)])
7. dict.keys()
Returns a view of the dictionary's keys.
Example:
d = {'a': 1, 'b': 2}
print(d.keys()) # Output: dict_keys(['a', 'b'])
8. dict.setdefault(key, default=None)
Returns the value of the key. If key is not present, inserts key with a default value.
Example:
d = {'a': 1}
print(d.setdefault('a', 100)) # Output: 1
print(d.setdefault('b', 200)) # Output: 200
9. dict.update(dict2)
Updates the dictionary with the key-value pairs from another dictionary.
Example:
d1 = {'a': 1}
d2 = {'b': 2}
d1.update(d2)
print(d1) # Output: {'a': 1, 'b': 2}
10. dict.values()
Returns a view of the dictionary's values.
Example:
d = {'a': 1, 'b': 2}
print(d.values()) # Output: dict_values([1, 2])