VOOZH about

URL: https://www.geeksforgeeks.org/python/use-get-method-to-create-a-dictionary-in-python-from-a-list-of-elements/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

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.


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.
Comment
Article Tags: