Skip to content
Related Articles

Related Articles

Use get() method to create a dictionary in Python from a list of elements

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 10 Jul, 2020
View Discussion
Improve Article
Save Article

Prerequisites: Get() method for dictionaries in Python

The naive approach for creating a dictionary from a list of items we can use the for loop. See the below example for better understanding.

Example:




li =['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a']
di ={}
  
for ele in li:
      
    # Increase the value of key
    # if exists
    if ele in di:
        di[ele]= di[ele]+1
    else:
          
        # Insert the new key:value
        # pair
        di[ele]= 1
  
print(di)


Output:

{'a': 3, 'b': 2, 'c': 1, 'd': 1, 'e': 1}

In the above code, a loop is used to iterate over the elements in the list. If the key is already present in the dictionary, then its value is incremented by 1, else it creates a new key for that element in the dictionary and assigns 1 as a value to it.

An alternative approach that can be used is by using the inbuilt .get() function in the Python library. See the below example for better understanding




li =['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a']
di ={}
  
for ele in li:
    di[ele]= di.get(ele, 0)+1
  
print(di)


Output:

{'a': 3, 'b': 2, 'c': 1, 'd': 1, 'e': 1}

In the above code, a loop is used to iterate over the elements in the list. The code at line 5 creates a key for every element in the list. If the key is already present in the dictionary then, it adds 1 to the value of it, else it creates a new key corresponding to the element and assigns 0 as a default value to it. Then it adds 1 to it to increase the count.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!