Python Dictionary Methods with Examples
1. [Link]()
Removes all elements from the dictionary.
Example:
d = {'a': 1, 'b': 2}
[Link]()
print(d) # Output: {}
2. [Link]()
Returns a shallow copy of the dictionary.
Example:
d1 = {'x': 10, 'y': 20}
d2 = [Link]()
print(d2) # Output: {'x': 10, 'y': 20}
3. [Link](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 = [Link](keys, 0)
print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
4. [Link](key, default=None)
Returns the value for the key if it exists, else returns the default.
Example:
d = {'a': 1}
print([Link]('a')) # Output: 1
print([Link]('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. [Link]()
Returns a view of the dictionary's (key, value) pairs.
Example:
d = {'a': 1, 'b': 2}
print([Link]()) # Output: dict_items([('a', 1), ('b', 2)])
7. [Link]()
Returns a view of the dictionary's keys.
Example:
d = {'a': 1, 'b': 2}
print([Link]()) # Output: dict_keys(['a', 'b'])
8. [Link](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([Link]('a', 100)) # Output: 1
print([Link]('b', 200)) # Output: 200
9. [Link](dict2)
Updates the dictionary with the key-value pairs from another dictionary.
Example:
d1 = {'a': 1}
d2 = {'b': 2}
[Link](d2)
print(d1) # Output: {'a': 1, 'b': 2}
10. [Link]()
Returns a view of the dictionary's values.
Example:
d = {'a': 1, 'b': 2}
print([Link]()) # Output: dict_values([1, 2])