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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.