![]() |
VOOZH | about |
We are given a list of elements and our task is to create a dictionary where each element serves as a key. If a key appears multiple times then we need to count its occurrences. get() method in Python helps achieve this efficiently by providing a default value when accessing dictionary keys. For example, given the list: a = ["apple", "banana", "apple", "orange", "banana", "apple"] then we should create the dictionary: {'apple': 3, 'banana': 2, 'orange': 1}
Instead of checking if the key exists we use get() to provide a default count of 0, making the code more concise and efficient.
{'apple': 3, 'banana': 2, 'orange': 1}
Explanation: