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

后端 未结 7 1133
别跟我提以往
别跟我提以往 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:16

    from collections import defaultdict
    adict = defaultdict(int)
    
    adict['a'] += 1
    adict['b'] += 3
    adict['c'] += 5
    adict['d'] += 2
    
    for key, value in sorted(adict.items(), lambda a, b: cmp(a[1], b[1]), reverse=True):
        print "%r => %r" % (key, value)
    
    >>> 
    'c' => 5
    'b' => 3
    'd' => 2
    'a' => 1
    

     

提交回复
热议问题