T
T
Tayrus02020-06-26 11:09:32
Python
Tayrus0, 2020-06-26 11:09:32

How to sort dictionary by value?

Have a dictionary

workers = {
    'empl1': '13150',
    'empl2': '11100',
    'empl3': '19500',
    'empl4': '3000',
    'empl5': '18000',
    'empl6': '8585',
    'empl7': '1',
    'empl8': '1',
    'empl9': '7000',
    'empl10': '7070',
    'empl11': '2730',
    'empl12': '11615',
    'empl13': '10000',
    'empl14': '7170',
    'empl15': '99999999',
    'empl16': '11000',
    'empl17': '4300',
    'empl18': '666',
    'empl19': '54000'
}

I want to sort it in ascending order, by values. I sort it like this:
sorted_by_value = sorted(workers.items(), key=lambda kv: kv[1], reverse=True)
print(dict(sorted_by_value))
But at the output I get the wrong sorting:
{
    'empl15': '99999999',
    'empl6': '8585',
    'empl14': '7170',
    'empl10': '7070',
    'empl9': '7000',
    'empl18': '666',
    'empl19': '54000',
    'empl17': '4300',
    'empl4': '3000',
    'empl11': '2730',
    'empl3': '19500',
    'empl5': '18000',
    'empl1': '13150',
    'empl12': '11615',
    'empl2': '11100',
    'empl16': '11000',
    'empl13': '10000',
    'empl7': '1',
    'empl8': '1'
}

Why and how to sort it?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vadim Shatalov, 2020-06-26
@Tayrus0

sorted_by_value = sorted(workers.items(), key=lambda kv: int(kv[1]), reverse=True)
... print(sorted_by_value)
[('empl15', '99999999'), ('empl19', '54000'), ('empl3', '19500'), ('empl5', '18000'), ('empl1', '13150'), ('empl12', '11615'), ('empl2', '11100'), ('empl16', '11000'), ('empl13', '10000'), ('empl6', '8585'), ('empl14', '7170'), ('empl10', '7070'), ('empl9', '7000'), ('empl17', '4300'), ('empl4', '3000'), ('empl11', '2730'), ('empl18', '666'), ('empl8', '1'), ('empl7', '1')]

D
Dmitry, 2020-06-26
@dimoff66

Because you are sorting by rows. If you want to sort by numbers, then
lambda kv: int(kv[1])

D
Dmitry, 2020-06-26
@LazyTalent

Python - Built-in Types

S
Sergey Pankov, 2020-06-26
@trapwalker

{
    key: value 
    for _, key, value in 
    sorted(
        (-int(v), k, v)
        for k, v in
        workers.items()
    )
}

M
meaqese, 2020-06-26
@meaqese

workers = {
    'empl1': '13150',
    'empl2': '11100',
    'empl3': '19500',
    'empl4': '3000',
    'empl5': '18000',
    'empl6': '8585',
    'empl7': '1',
    'empl8': '1',
    'empl9': '7000',
    'empl10': '7070',
    'empl11': '2730',
    'empl12': '11615',
    'empl13': '10000',
    'empl14': '7170',
    'empl15': '99999999',
    'empl16': '11000',
    'empl17': '4300',
    'empl18': '666',
    'empl19': '54000'
}

sorted_dict = sorted(workers.items(), key=lambda worker: int(worker[1]))
print(sorted_dict)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question