Dictionaries are one of the data type in Python, representing key-value pairs. Dictionaries are commonly used for storing and manipulating data where a unique identifier, or key, is associated with a specific value. Python provides several methods for working with dictionaries, and in this article, we will discuss some of the most commonly used dictionary methods.
1) dict.keys(): This method returns a dict_keys object of all keys present in a dictionary.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} print(a.keys()) # Output: dict_keys(['aa', 'bb', 'cc'])
2) dict.values(): This method returns a dict_values object of all values present in a dictionary.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} print(a.values()) # Output: dict_values([100, 200, 300])
3) dict.items(): This method returns a dict_items object of all key-value pairs present in a dictionary.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} print(a.items()) # Output: dict_items([('aa', 100), ('bb', 200), ('cc', 300)])
4) dict.get(): This method return the value of a specified key in a dictionary. If the key is not found in the dictionary then it returns a default value mentioned in the get() method.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} print(a.get('d', 0)) # Output: 0
5) dict.update(): This method updates a dictionary with key-value pairs from another dictionary or iterable.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} b = {'d': 400, 'e': 500} a.update(b) print(a) # Output: {'aa': 100, 'bb': 200, 'cc': 300, 'd': 400, 'e': 500}
6) dict.pop(): This method removes and returns the value of a specified key in a dictionary. If the key is not found, a KeyError is raised.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} print(a.pop('bb')) # Output: 200 print(a) # Output: {'aa': 100, 'cc': 300}
7) dict.clear(): This method removes all items (key-value pairs) from a dictionary.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} a.clear() print(a) # Output: {}
8) dict.fromkeys(): This method return the new dictionary with a key from the iterable and default value assign to all the keys.
For example:
b = [100, 200, 300, 400, 500] c = dict.fromkeys(b, 'aa') print(c) # Output: {100: 'aa', 200: 'aa', 300: 'aa', 400: 'aa', 500: 'aa'} e = {} f = e.fromkeys(b, 'aa') print(f) # Output: {100: 'aa', 200: 'aa', 300: 'aa', 400: 'aa', 500: 'aa'}
9) len(): This is built-in function which returns the number of items(key-value pairs) present in a dictionary.
For example:
a = {'aa': 100, 'bb': 200, 'cc': 300} print(len(a)) # Output: 3
In conclusion, these are some of the most commonly used dictionary methods in Python. Dictionaries provide a powerful and flexible way to store and manipulate data where each value is associated with a unique key. By understanding and using these methods, we can effectively work with dictionaries in Python.