Search code examples
pythondictionarycounter

Display each element of the dictionary on a new line working with Counter


I have an array with random colors. There are duplicate elements. For example:

mass = ['white','black','white'...]

I need to count them so I've decided to use Counter:

mass_count = Counter(mass)
print (mass_count)

What I've got

I want to display each element of the dictionary on a new line. I've used that code:

keys = [k for k in mass_count]
for i, key in enumerate(keys):      
    print("\n" + str(list(mass_count.keys())[i]) + ": " + str(mass_count[keys[i]]))

What I've got #2

Everything as I want except one thing: There are all elements displaying from max to min on my first result but this order is violated on the second result. So I want:

White: 22

Black: 14

Sky blue: 6

...

How can I achieve it? Thank you.


Solution

  • you can use Counter.most_common() method

    for color, value in mass_count.most_common():
        print(f"{color}: {value}")