Python通过特定列对多维dict进行排序

时间:2017-04-25 18:05:50

标签: python sorting lambda

我知道有很多关于这方面的问题,但我试图通过命中专栏对下面的字典进行排序。

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

请问我能得到一些帮助吗?

谢谢!

2 个答案:

答案 0 :(得分:6)

迭代dict会生成键,因此您需要再次在dict中查找x

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

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

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

答案 1 :(得分:3)

使用dict作为迭代只会导致键被迭代而不是值,因此lambda中的x只会是“a”,“b”和“c”你基本上是执行"a"["hitrate"],这会导致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']