2017-04-25 52 views
2

我知道有很多关于这个问题的问题,但我试图通过hitrate列来排序下面的字典。Python按特定列排序多维字典

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 

我能得到一些帮助,这好吗?

谢谢!

回答

5

迭代的字典产生的钥匙,所以你需要再次查找x在字典:

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

使用字典作为迭代只会导致键被迭代,而不是值,所以x在你的lambda只会是“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'] 
+0

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

如果你想要的值过,然后对项目进行排序真棒!非常感谢! –