How to sort keys of dict by values?

前端 未结 5 1716
忘掉有多难
忘掉有多难 2021-01-19 11:13

I have a dict {\'a\': 2, \'b\': 0, \'c\': 1}.

Need to sort keys by values so that I can get a list [\'b\', \'c\', \'a\']

Is there a

相关标签:
5条回答
  • 2021-01-19 11:52
     sorted_keys = sorted(my_dict, key=my_dict.get)
    
    0 讨论(0)
  • 2021-01-19 11:59

    There's a simple way to do it. You can use .items() to get key-value and use sorted to sort them accordingly.

    dictionary = sorted(dictionary.items(),key=lambda x:x[1])
    
    0 讨论(0)
  • 2021-01-19 12:01

    try this:

    import operator
    lst1 = sorted(lst.items(), key=operator.itemgetter(1))
    
    0 讨论(0)
  • 2021-01-19 12:01
    >>> d = {'a':2, 'b':0, 'c':1}
    >>> sor = sorted(d.items(), key=lambda x: x[1])
    >>> sor
    [('b', 0), ('c', 1), ('a', 2)]
    >>> for i in sor:
    ...     print i[0]
    ...
    b  
    c 
    a
    
    0 讨论(0)
  • 2021-01-19 12:05
    >>> d={'a': 2, 'b': 0, 'c': 1}
    >>> [i[0] for i in sorted(d.items(), key=lambda x:x[1])]
    ['b', 'c', 'a']
    
    0 讨论(0)
提交回复
热议问题