python按值排序字典项,然后键

时间:2015-12-08 13:13:01

标签: python sorting dictionary items

所有

我很难按值排序字典,然后打印。

我的对象(dataSet)如下所示......

dict_items([(0, {'studentName': 'dan', 'Score': 80.0}), (1, {'studentName': 'rob', 'Score': 92.0})])

我想按分数和打印排序,但我失败了。我建议使用以下方法按StudentName排序,如果有帮助的话。

entries = sorted([(dataSet[entry]['studentName'], dataSet[entry]['Score']) for entry in dataSet])
  for name, score in entries:
    print(('Student: {} -- Score: {}%'.format(name, score)))

5 个答案:

答案 0 :(得分:3)

MyDict = {0: {'Score': 80.0, 'studentName': 'dan'},
          1: {'Score': 92.0, 'studentName': 'rob'},
          2: {'Score': 10.0, 'StudentName': 'xyz'}}

这将返回字典中键值对的列表,按值从最高到最低排序:

sorted(MyDict.items(), key=lambda x: x[1], reverse=True)

对于按键排序的字典,请使用以下命令:

sorted(MyDict.items(), reverse=True)

返回是一个元组列表,因为字典本身无法排序。

这可以打印或发送到进一步的计算中。

答案 1 :(得分:1)

如果您只需要按分数值排序的按键列表:

d = {0: {'Score': 80.0, 'studentName': 'dan'},
     1: {'Score': 92.0, 'studentName': 'rob'},
     2: {'Score': 10.0, 'studentName': 'xyz'}}

sorted(d, key=lambda k: d[k]['Score'])

产生

[2, 0, 1]

否则,您可以使用有序词典

from collections import OrderedDict
od = OrderedDict(sorted(d.items(), key=lambda i: i[1]['Score']))

给你

OrderedDict([(0, {'Score': 80.0, 'studentName': 'dan'}), (1, {'Score': 92.0, 'studentName': 'rob'})])

你可以很好地打印

for v in od.values():
    print(v['Score'], v['studentName'])

10.0 xyz
80.0 dan
92.0 rob

答案 2 :(得分:1)

假设您的对象是list tuples dicts {我可以通过给出的数据得到最接近的解释),这就足够了:

>>> dict_items = [(0, {'Score': 80.0, 'studentName': 'dan'}), (1, {'Score': 92.0, 'studentName': 'rob'
})]
>>> sorted(dict_items, key=lambda x: x[1]['Score'])
# [(0, {'Score': 80.0, 'studentName': 'dan'}), (1, {'Score': 92.0, 'studentName': 'rob'
})]

答案 3 :(得分:1)

另一种方法如下,也许有人需要:

d = {0: {'Score': 80.0, 'studentName': 'dan'},
     1: {'Score': 92.0, 'studentName': 'rob'},
     2: {'Score': 10.0, 'StudentName': 'xyz'}}

sorted(d, cmp = lambda a,b: cmp(d[a]['Score'],d[b]['Score']))

答案 4 :(得分:1)

我会用:

 def comp(x,y):
    if x[1]['Score'] != y[1]['Score']:
        return 1 if x[1]['Score'] > y[1]['Score'] else -1
    elif x[1]['studentName'] < y[1]['studentName']:
        return -1
    elif x[1]['studentName'] > y[1]['studentName']:
        return 1
    else:
        return 0

然后

sorted(dict_items, comp)

例如

dict_items = [(0, {'Score': 80.0, 'studentName': 'dan'}),
              (1, {'Score': 92.0, 'studentName': 'rob'}),
              (2, {'Score': 70.0, 'studentName': 'foo'})]

它给出了:

[(2, {'Score': 70.0, 'studentName': 'foo'}), (0, {'Score': 80.0, 'studentName': 'dan'}),
 (1, {'Score': 92.0, 'studentName': 'rob'})]

但是要小心:您的问题标题是 dictionnary 项目。答案与问题中的代码一致,但只排序元组列表。如果您确实有词典d,则应使用sorted(d.items())