【问题标题】:How to sort a Python dict's keys by value如何按值对 Python dict 的键进行排序
【发布时间】:2011-03-25 23:16:24
【问题描述】:

我有一个看起来像这样的字典

{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }

我想将其转换为 DESC 并创建一个仅包含关键字的列表。例如,这将返回

["keyword3" , "keyword1" , "keyword4" , "keyword2"]

我发现的所有示例都使用 lambda,但我对此不是很擅长。有没有办法可以循环遍历它,并在我去的时候对它们进行排序?感谢您的任何建议。

PS:如果有帮助,我可以创建不同的初始字典。

【问题讨论】:

标签: python sorting dictionary


【解决方案1】:

你可以使用

res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))

(在 Python 2.x 中您不需要 list

theDict.__getitem__ 实际上等价于lambda x: theDict[x]

(lambda 只是一个匿名函数。例如

>>> g = lambda x: x + 5
>>> g(123)
128

这相当于

>>> def h(x):
...   return x + 5
>>> h(123)
128

)

【讨论】:

  • +1 用于对包含整数的文件名进行数字排序。 names = {} for f in sys.argv[1:] : robj = re.search( "([0-9]+)", f ) 如果 robj 不是 None : names[f] = int(robj.group (1)) res = list(sorted(names,key=names.__getitem__)) print "\n".join(res)
【解决方案2】:

我一直都是这样做的……使用 sorted 方法有什么好处吗?

keys = dict.keys()
keys.sort( lambda x,y: cmp(dict[x], dict[y]) )

哎呀没有阅读关于不使用 lambda =(

的部分

【讨论】:

    【解决方案3】:

    我会想出这样的东西:

    [k for v, k in sorted(((v, k) for k, v in theDict.items()), reverse=True)]
    

    但是KennyTM's solution 更好:)

    【讨论】:

      【解决方案4】:
      >>> d={ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
      >>> sorted(d, key=d.get, reverse=True)
      ['keyword3', 'keyword1', 'keyword4', 'keyword2']
      

      【讨论】:

        【解决方案5】:

        无法对 dict 进行排序,只能得到已排序的 dict 的表示。字典本质上是无序的,但其他类型,例如列表和元组,则不是。所以你需要一个排序的表示,它是一个列表——可能是一个元组列表。例如,

        '''
        Sort the dictionary by score. if the score is same then sort them by name 
        { 
         'Rahul'  : {score : 75} 
         'Suhas' : {score : 95} 
         'Vanita' : {score : 56} 
         'Dinesh' : {score : 78} 
         'Anil'  : {score : 69} 
         'Anup'  : {score : 95} 
        } 
        '''
        import operator
        
        x={'Rahul' : {'score' : 75},'Suhas' : {'score' : 95},'Vanita' : {'score' : 56}, 
           'Dinesh' : {'score' : 78},'Anil' : {'score' : 69},'Anup' : {'score' : 95} 
          }
        sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
        print sorted_x
        

        输出:

        [('Vanita', {'score': 56}), ('Anil', {'score': 69}), ('Rahul', {'score': 75}), ('Dinesh', {'score': 78}), ('Anup', {'score': 95}), ('Suhas', {'score': 95})]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-09
          • 2021-10-19
          • 2013-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多