python, convert a dictionary to a sorted list by value instead of key

后端 未结 7 1182
别跟我提以往
别跟我提以往 2021-02-04 03:45

I have a collections.defaultdict(int) that I\'m building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turnin

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 04:18

    "Invert" a dictionary.

    from collections import defaultdict
    inv_dict = defaultdict( list )
    for key, value in adict:
        inv_dict[value].append( key )
    max_value= max( inv_dict.keys() )
    

    The set of keys with the maximum occurrence --

    inv_dict[max_value] 
    

    The set of keys in descending order by occurrence --

    for value, key_list in sorted( inv_dict ):
        print key_list, value
    

提交回复
热议问题