transform a dictionary from key:value to value:number of occurences

Let's say I have a dictionary as follows

d = {1: 7, 2: 8, 3: 9, 4: 7, 5: 8, 6: 9, 7: 7, 8: 8, 9: 9, 10: 9}

How can I get a dictionary of the most common values sorted in descending order?

So I would expect

res = {9: 4, 8: 3, 7: 3}

Answers


Use collections.Counter:

>>> from collections import Counter
>>> d = {1: 7, 2: 8, 3: 9, 4: 7, 5: 8, 6: 9, 7: 7, 8: 8, 9: 9, 10: 9}
>>> Counter(d.values())
Counter({9: 4, 8: 3, 7: 3})
>>> Counter(d.values()).most_common()
[(9, 4), (8, 3), (7, 3)]

Need Your Help

How to force youtube to play HD videos

html video youtube youtube-api videoview

I have below video in frame and forcefully wants to run it on High Quality at first go

Capture and insert Unicode text (Cyrillic) into MS access database

ms-access vbscript asp-classic ms-access-2007 cyrillic

I inherited an old web application, that is writing data collected in a form into an Access 2007 database using classic ASP.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.