Open In App

Use get() method to Create a Dictionary in Python from a List of Elements

Last Updated : 04 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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}

Using get()

Instead of checking if the key exists we use get() to provide a default count of 0, making the code more concise and efficient.

a = ["apple", "banana", "apple", "orange", "banana", "apple"]

d = {}
for item in a:
    d[item] = d.get(item, 0) + 1

print(d) 

Output
{'apple': 3, 'banana': 2, 'orange': 1}

Explanation:

  • d.get(item, 0) retrieves the current count (defaulting to 0 if the key is missing) and we simply add 1 to update the count.
  • This approach removes the need for explicit conditional checks making it cleaner and more efficient.


Next Article

Similar Reads

three90RightbarBannerImg