Python Exercise 11: Count the number and generate new dictionary

mathewchan

HHMathewChan

Posted on June 15, 2022

Python Exercise 11: Count the number and generate new dictionary

Question

  • Write a program to iterate a given list and count the occurrence of each element and create a to show the count of each element.
  • Given:
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
Enter fullscreen mode Exit fullscreen mode
  • Expected Output:
Printing count of each item   {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
Enter fullscreen mode Exit fullscreen mode

My solution

  1. initiate an empty dictionary
  2. initiate an counter
  3. iterate over the sample_list
    • 3.1 for each number, count the occurrence of that number in sample
    • 3.2 use setdefault() method to add the number as key and occurrence as value to dictionary
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]  
count_dictionary = dict()
occurrence = 0
for number in sample_list:  
    occurrence = sample_list.count(number)  
    count_dictionary.setdefault(number, occurrence)  


print(f"Printing count of each item {count_dictionary}")
Enter fullscreen mode Exit fullscreen mode

Other Solution

  1. initiate an empty dictionary
  2. iterate over the sample_list
    • 2.1 check if the number appear in the dictionary
      • 2.1.1 if the number does not appear in the dictionary, add the number as key and 1 as value to the dictionary
      • 2.1.2 if the appear in the dictionary, increase the value by 1.
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sample_list)

count_dict = dict()
for item in sample_list:
    if item in count_dict:
        count_dict[item] += 1
    else:
        count_dict[item] = 1

print("Printing count of each item  ", count_dict)


Enter fullscreen mode Exit fullscreen mode

Credit

exercise on Pynative

💖 💪 🙅 🚩
mathewchan
HHMathewChan

Posted on June 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related