DEV Community

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

4 3

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more