Sort Dictionary by Value in Python – How to Sort a Dict
Kolade Chris

In Python, a dictionary is a fat structure that is unordered by default. So, sometimes, you’ll want to sort dictionaries by key or value to make queries easier.
The problem is that sorting a dictionary by value is never a straightforward thing to do. That’s because Python doesn’t have an inbuilt method to do it.
However, I figured out a way to sort dictionaries by value, and that’s what I’m going to show you how to do in this article.
What We’ll Cover
How to Sort Data with the sorted() Method
The sorted() method sorts iterable data such as lists, tuples, and dictionaries. But it sorts by key only.
The sorted() method puts the sorted items in a list. That’s another problem we have to solve, because we want the sorted dictionary to remain a dictionary.
For instance, sorted() arranged the list below in alphabetical order:
And the sorted() method sorts the numbers in the tuple below in ascending order:
If you use the sorted() method with a dictionary, only the keys will be returned and as usual, it will be in a list:
This is not the behavior you want. You want the dictionary to be sorted by value and remain a dictionary. That’s what I’m going to show you next.
How the sorted() Method Works
To sort a dictionary, we are still going to use the sorted function, but in a more complicated way. Don’t worry, I will explain everything you need to know.
Since we are still going to use the sorted() method, then it’s time to explain the sorted() method in detail.
Parameters of the sorted() Method
The sorted() method can accept up to 3 parameters:
iterable – the data to iterate over. It could be a tuple, list, or dictionary.
key – an optional value, the function that helps you to perform a custom sort operation.
reverse – another optional value. It helps you arrange the sorted data in ascending or descending order
If you guess it right, the key parameter is what we’ll pass into the sorted() method to get the dictionary sorted by value.
Now, it’s time to sort our dictionary by value and make sure it remains a dictionary.
How to Sort a Dictionary with the sorted() Method
To correctly sort a dictionary by value with the sorted() method, you will have to do the following:
- pass the dictionary to the sorted() method as the first value
- use the items() method on the dictionary to retrieve its keys and values
- write a lambda function to get the values retrieved with the item() method
Here’s an example:
As I said earlier, we have to get those values of the dictionary so we can sort the dictionary by values. That’s why you can see 1 in the lambda function.
1 represents the indexes of the values. The keys are 0. Remember that a programmer starts counting from 0, not 1.
With that code above, I got the result below:
Here’s the full code so you don’t get confused:
You can see the dictionary has been sorted by values in ascending order. You can also sort it in descending order. But we’ll look at that later because we still have a problem with the result we got.
The problem is that the dictionary is not a dictionary anymore. The individual keys and values were put in a tuple and further condensed into a list. Remember that whatever you get as the result of the sorted() method is put in a list.
We’ve been able to sort the items in the dictionary by value. What’s left is converting it back to a dictionary.
How to Convert the Resulting List to a Dictionary
To convert the resulting list to a dictionary, you don’t need to write another complicated function or a loop. You just need to pass the variable saving the resulting list into the dict() method.
Remember we saved the sorted dictionary in the variable named sorted_footballers_by_goals , so it’s the variable we have to pass to dict() .
The full code looks like this:
That’s it! We’ve been able to sort the items in the dictionary and convert them back to a dictionary. We’ve just had our cake and ate it as well!
How to Sort the Dictionary by Value in Ascending or Descending Order
Remember the sorted() method accepts a third value called reverse .
reverse with a value of True will arrange the sorted dictionary in descending order.
You can see the output is reversed because we passed reverse=True to the sorted() method.
If you don’t set reverse at all or you set its value to false, the dictionary will be arranged in ascending order. That’s the default.
Conclusion
Congratulations. You can now sort a dictionary by value despite not having a built-in method or function to use in Python.
However, there’s something that raised my curiosity when I was preparing to write this article. Remember we were able to use sorted() directly on a dictionary. This got us a list as the result, though we only got the keys and not the values.
What if we convert that list to a dictionary with the dict() method? Do you think we can get the desired result? Let’s see:
We got an error! That’s because if you want to create a dictionary from a list, you have to use dictionary comprehension. And if you use dictionary comprehension for this type of data, you’d have to specify one value for all the entries. That would defy the purpose of sorting a dictionary by value, so it’s not what we want.
If you want to learn more about dictionary comprehension, you should read this article.
Sorting HOW TO¶
Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
In this document, we explore the various techniques for sorting data using Python.
Sorting Basics¶
A simple ascending sort is very easy: just call the sorted() function. It returns a new sorted list:
You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it’s less convenient than sorted() — but if you don’t need the original list, it’s slightly more efficient.
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.
Key Functions¶
Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
For example, here’s a case-insensitive string comparison:
The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
A common pattern is to sort complex objects using some of the object’s indices as keys. For example:
The same technique works for objects with named attributes. For example:
Operator Module Functions¶
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter() , attrgetter() , and a methodcaller() function.
Using those functions, the above examples become simpler and faster:
The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
Ascending and Descending¶
Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse age order:
Sort Stability and Complex Sorts¶
Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.
Notice how the two records for blue retain their original order so that (‘blue’, 1) is guaranteed to precede (‘blue’, 2) .
This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:
This can be abstracted out into a wrapper function that can take a list and tuples of field and order to sort them on multiple passes.
The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.
Decorate-Sort-Undecorate¶
This idiom is called Decorate-Sort-Undecorate after its three steps:
First, the initial list is decorated with new values that control the sort order.
Second, the decorated list is sorted.
Finally, the decorations are removed, creating a list that contains only the initial values in the new order.
For example, to sort the student data by grade using the DSU approach:
This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.
It is not strictly necessary in all cases to include the index i in the decorated list, but including it gives two benefits:
The sort is stable – if two items have the same key, their order will be preserved in the sorted list.
The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly.
Another name for this idiom is Schwartzian transform, after Randal L. Schwartz, who popularized it among Perl programmers.
Now that Python sorting provides key-functions, this technique is not often needed.
Comparison Functions¶
Unlike key functions that return an absolute value for sorting, a comparison function computes the relative ordering for two inputs.
For example, a balance scale compares two samples giving a relative ordering: lighter, equal, or heavier. Likewise, a comparison function such as cmp(a, b) will return a negative value for less-than, zero if the inputs are equal, or a positive value for greater-than.
It is common to encounter comparison functions when translating algorithms from other languages. Also, some libraries provide comparison functions as part of their API. For example, locale.strcoll() is a comparison function.
To accommodate those situations, Python provides functools.cmp_to_key to wrap the comparison function to make it usable as a key function:
Odds and Ends¶
For locale aware sorting, use locale.strxfrm() for a key function or locale.strcoll() for a comparison function. This is necessary because “alphabetical” sort orderings can vary across cultures even if the underlying alphabet is the same.
The reverse parameter still maintains sort stability (so that records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin reversed() function twice:
The sort routines use < when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an __lt__() method:
However, note that < can fall back to using __gt__() if __lt__() is not implemented (see object.__lt__() ).
Key functions need not depend directly on the objects being sorted. A key function can also access external resources. For instance, if the student grades are stored in a dictionary, they can be used to sort a separate list of student names:
Сортировка словаря Python: как сортировать по значению, по ключу
![]()
В Python присутствует возможность хранить определенную информацию в словарях. Словарь в Питоне — это способ сохранить данные, используя форму «ключ-значение». Каждому отдельному ключу соответствует определенное значение. Данные в словаре изменяемые, поэтому структура в словарях чаще всего неупорядоченная. Для того чтобы упорядочить данные, используется сортировка словаря Python по ключу или значению.
Значения в словаре могут быть разными и даже повторяющимися, а ключ всегда уникальный. Словарь в Python обозначается ф игурными скобкам и , а сохраняемые пары «ключ-значение» отделяются з апято й . Вот как выглядит примитивный словарь Python в коде:
myDictionary =
Словарь очень похож на список Python, но отличается от него более легким поиском элементов, поэтому словарь считается быстрее списка. Однако, чтобы удобно работать со словарем, нужна сортировка словаря. Именно об этом мы сегодня и поговорим.
Сортировка словаря Python
-
keys() — для сортировки словаря по ключам ;
-
values() — для сортировки словаря по значениям.
Сортировка словаря Python по ключам
Это наиболее правильный вид сортировки, потому что обращаться к элементам словаря можно только по ключам. Когда осуществляется сортировка словаря Python по значениям, приходится немного «потрудит ь ся», потому что напрямую только к значениям словаря Питона обратиться нельзя. Об этом чуть ниже, а пока — вот как осуществляется сортировка словаря Python по ключам с использованием функции «keys()»:
names =
#выводим отсортированные ключи словаря
print(sorted(names.keys()))
#выводим отсортированный словарь целиком
print(sorted(names.items()))
В результате мы получим следующее:
#отсортированные ключи словаря
[1, 2, 3, 4, 5, 6]
#отсортированный словарь
[(1, ‘Алиса’), (2, ‘Иван’), (3, ‘Андрей’), (4, ‘Петр’), (5, ‘Яна’), (6, ‘Дормидонт’)]
Фактически при таком подходе сортировки словаря происходит создание списка ключей, потом ключи сортируются. При необходимости можно вывести либо отсортированные ключи, либо весь словарь.
Сортировка словаря Python по значениям
-
напрямую к значения м обратиться сложно;
-
используя данный вид сортировки, невозможно отсортировать информацию в том же словаре, поэтому создается новый словарь с отсортированными значениями.
Заключение
Сегодня мы показали , как происходит сортировка словаря Python по ключу и по значению. Разные виды сортировки дают разный конечный результат , п оэтому выбор алгоритма сортировки имеет значени е .
Раньше словарь Python приходилось сортировать, используя циклы «for» , в этом случае код очень сильно «раздувался». Но с приходом специальной функции «sorted()» сортировка словаря Python стала более компактной и понятной.
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
28. Внутреннее устройство и сортировка словаря в Python
В уроке 6.5. мы научились сортировать списки. Сортировка словаря имеет свои особенности, с которыми будем разбираться в этом уроке. Так же глубже разберемся с тем, что такое словарь и как он реализуется в Python (точнее, в интерпретаторе CPython).
Начиная с версии Python 3.7. словари стали упорядоченными. В ранних версиях Python при запуске программы, порядок ключей словаря мог меняться. То есть вы инициализировали следующий словарь:
Вывод словаря number мог быть как таким:
Чтобы это понять, погрузимся во внутреннее устройство словарей в Python.
Внутреннее устройство словарей в Python
Этот материал представлен для ознакомления. Он может показаться сложным, поэтому можете его пропустить и вернуться к нему позднее. Если вам интересно, почему после версии Python 3.6. словарь реализован с помощью двух массивов и как это повлияло на сохранение порядка вставки элементов, то продолжайте чтение или перейдите сразу к сортировке словарей в Python.
Предположим, у нас есть массив, в котором хранятся объекты одного размера. Тогда зная индекс и размер одного объекта, мы легко можем получить доступ к нужному объекту.
Но что делать, если индексом является объект нецелочисленного типа, например, строка? В таком случае нам придется просматривать каждый элемент массива, чтобы найти нужный, другими словами, произвести линейный поиск.
Линейный поиск может быть значительно ускорен, для чего потребуется ограничить область поиска. Это достигается путем взятия остатка от деления хэша. Хэш-функция — это функция, принимающая данные любой длины, преобразующая их по определенному алгоритму и возвращающая строку фиксированной длины. Поле, по которому будет осуществляться дальнейший поиск, называется ключом.
Существует вероятность, что кэши совпадут. В таком случае объект будет размещен под следующим индексом, если он свободен. Если следующий индекс занят, то будет проверен последующий и так до тех пор, пока не найдется свободный.
При поиске необходимого элемента под одним хэшем окажется несколько элементов, из которых будет найден нужный при помощи линейного поиска. То есть, чем больше элементов будут иметь одинаковые хэши, тем меньше выигрыш от использования словаря.
После заполнения массива на две трети, создаётся новый массив размером в два раза больше предыдущего и в него переносятся элементы по одному.
При удалении элемента, он помечается DKIX_DUMMY , чтобы не было путаницы: этот элемент был удален или это пустая ячейка.
В Python каждый элемент словаря содержит ссылку на хранимый объект и ключ. Ключ необходимо хранить для разрешения коллизий, которые возникают при совпадении хэша у элементов. Итак, а что произойдет, если ключ словаря был изменён? Ничего, потому что ключ словаря изменить нельзя, так как ключом может быть только неизменяемый объект.
В Python минимальный размер словаря равен восьми. Исходя из вышесказанного, первое расширение словаря будет осуществлено при добавлении 6 элемента. Таким образом, в массиве всегда много пустых ячеек. Чтобы это исправить, в версии Python 3.6. добавили второй массив для реализации словаря.
До версии Python 3.6. словарь был реализован одним массивом:
Как видите, наш словарь состоит из трех элементов, поэтому был создан массив из восьми элементов. Каждый элемент хранит хэш, ключ и значение. После версии Python 3.6. был добавлен второй массив.
В первом массиве хранятся только индексы соответствующих записей, а во втором сами записи. Таким образом, на хранение двух массивов стало уходить меньше памяти, а порядок элементов стал неизменным.
Сортировка словаря в Python
Сортировать словари в Python можно как по ключу, так и по значению. В уроке 7.4. вы познакомились с методом словаря items() , который возвращает кортеж из двух элементов. Зная это, можем отсортировать словарь по ключу следующим образом:
Помните, что функция sorted() не изменяет объект, переданный ей в параметре, а возвращает новый. Об этом мы говорили в уроке 6.5. Так вот, мы отсортировали словарь, который был сначала преобразован в список кортежей:
Потом обратно собрали в словарь:
Есть другой способ сортировать словарь по ключам. По сути, это сводится к сортировке списка и использованию встроенного метода sort() для них. Для этого получим список ключей словаря при помощи метода keys() и выведем словарь согласно отсортированным ключам:
Сортировка словаря в Python по значению немного сложнее. Осложняет еще и то, что мы не знакомились с лямбда ( lambda ) выражениями. Поэтому будем использовать встроенный модуль operator , который необходимо подключить при помощи ключевого слова import .
В уроке 6.5. параметр key мы использовали, чтобы сортировать строки независимо от регистра. Теперь в параметр key будем передавать второй элемент кортежа, который является значением элемента в словаре.
Для этого будем использовать itemgetter() , который возвращает n-ый элемент в итерируемом объекте. Полный пример сортировки словаря по значению представлен ниже.
Для примера, отсортируем список кортежей из трех элементов при помощи itemgetter() , чтобы лучше понять, что означает передаваемый параметр.
В этом уроке мы разобрались, как реализован словарь в Python на уровне интерпретатора и научились сортировать словари по ключу и значению.