简体   繁体   中英

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]
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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM