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

后端 未结 7 1132
别跟我提以往
别跟我提以往 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条回答
  •  猫巷女王i
    2021-02-04 04:22

    If you're using the newest python 2.7 alpha, then you can use the Counter class in collections module:

    c = Counter()
    
    c['someval'] += 1
    c['anotherval'] += 1
    c['someval'] += 1
    
    print c.most_common()
    

    prints in the correct order:

    [('someval', 2), ('anotherval', 1)]
    

    The code used on 2.7 is available already and there's a version adapted to 2.5. Perhaps you want to use it to stay forward compatible with the native stdlib version that is about to be released.

提交回复
热议问题