'How does one sort dictionary values?
Is there a way to sort (and return) a dictionary by multiple values? The below returns the values in a list. I'd like to improve on the below and also return the keys so that the returned data structure is a sorted dictionary.
df = pd.DataFrame([[-1,1,-1,3,1,2]], index =
pd.date_range(start = '2022-02-07', periods =1, name = 'Date'))
df.columns = pd.MultiIndex.from_tuples((("IINN", "s"), ("IINN", "count"),
("GII", "s"), ("GII","count"),("HCM","s"), ("HCM", "count")))
dct={c:df[c] for c in df.columns.levels[0]}
sorted(dct.values(),key = lambda item: (item['s'][-1],item['count'][-1]), reverse=True)
[ s count
Date
2022-02-07 1 2,
s count
Date
2022-02-07 -1 3,
s count
Date
2022-02-07 -1 1]
Solution 1:[1]
from operator import itemgetter
from typing import Any, Iterator
DCT = {
'foo': 1,
'bar': 2,
'spamm': 0
}
print(DCT)
def sort_by_values(dct: dict) -> Iterator[tuple[Any, Any]]:
"""Yields dict items sorted by their values."""
for key, value in sorted(dct.items(), key=itemgetter(1)):
yield key, value
for key, value in sort_by_values(DCT):
print(key, value)
print(dict(sort_by_values(DCT)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard Neumann |
