Answer the question
In order to leave comments, you need to log in
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'
}
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'
}
Answer the question
In order to leave comments, you need to log in
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')]
Because you are sorting by rows. If you want to sort by numbers, then
lambda kv: int(kv[1])
{
key: value
for _, key, value in
sorted(
(-int(v), k, v)
for k, v in
workers.items()
)
}
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 questionAsk a Question
731 491 924 answers to any question