【问题标题】:Python sorting multidimensional dict by a specific columnPython按特定列对多维字典进行排序
【发布时间】:2017-09-22 21:35:26
【问题描述】:

我知道有很多关于此的问题,但我正在尝试按 hitrate 列对下面的 dict 进行排序。

data = {
    'a': {'get': 1, 'hitrate': 1, 'set': 1},
    'b': {'get': 4, 'hitrate': 20, 'set': 5},
    'c': {'get': 3, 'hitrate': 4, 'set': 3}
}

我尝试了很多东西,最有希望的是下面的方法似乎出错了。

s = sorted(data, key=lambda x: int(x['hitrate']))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: string indices must be integers, not str

我能得到一些帮助吗?

谢谢!

【问题讨论】:

    标签: python sorting dictionary lambda


    【解决方案1】:

    迭代一个字典会产生键,所以你需要再次在字典中查找x

    sorted(data, key=lambda x: int(data[x]['hitrate']))
    

    如果您也想要这些值,请对项目进行排序:

    sorted(data.items(), key=lambda item: int(item[1]['hitrate']))
    

    【讨论】:

      【解决方案2】:

      使用 dict 作为可迭代对象只会导致键被迭代,而不是值,所以你的 lambda 中的 x 只会是 "a"、"b" 和 "c" 你基本上是在做 @ 987654322@,这会导致 TypeError。尝试使用 x 作为字典的键。

      >>> data = {
      ...     'a': {'get': 1, 'hitrate': 1, 'set': 1},
      ...     'b': {'get': 4, 'hitrate': 20, 'set': 5},
      ...     'c': {'get': 3, 'hitrate': 4, 'set': 3}
      ... }
      >>> s = sorted(data, key=lambda x: int(data[x]['hitrate']))
      >>> s
      ['a', 'c', 'b']
      

      【讨论】:

      • 太棒了!非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      相关资源
      最近更新 更多