Home python Sorting dictionary by value (decrease)

Sorting dictionary by value (decrease)

Author

Date

Category

There is a dictionary, key (city) and value (calculation formula% -s).
It is necessary to output the pair of , sorted by descending value .

Tell me, please, how can this be done?

arizona = 1200
Arizona_Limit = 1899.
BOSTON = 561.
BOSTON_LIMIT = 3622.
California = 5800.
California_Limit = 8900.
DENVER = 15000.
DENVER_LIMIT = 80000.
#DICTIONARY
Every_one = {'arizona': ((Arizona * 100) / Arizona_Limit),
       'BOSTON': ((Boston * 100) / Boston_Limit),
       'California': ((California * 100) / California_Limit),
       'DENVER': ((Denver * 100) / denver_limit)}
Print (every_one)

Answer 1, Authority 100%

You can generate a new dictionary based on the list obtained by the sorted function, which the function of obtaining a value of the key from the dictionary (get ) was transferred as a sort key.

Example (python3.7 +):

d = {'arizona': 63.191153238546605, 'BOSTON': 15.48868028713418, 'California': 65.1685393258427, 'DENVER' : 18.75}
d = {k: d [k] for k in sorted (d, key = d.get, reverse = true)}
Print (D)

stdout:

{'California': 65.1685393258427, 'arizona': 63.191153238546605, 'DENVER': 18.75, 'BOSTON': 15.48868028713418 }

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions