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

时间:2021-08-31 07:40:36

All,

所有,

I'm having difficulty sorting a dictionary by value and then printing.

我无法按值排序字典然后打印。

My object (dataSet) looks like the following...

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

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

I would like to sort by Score and print, but I am failing miserably. I used the following method as advised to sort by StudentName, if it is of help.

我想按分数和打印排序,但我失败了。我建议使用以下方法按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 个解决方案

#1


3  

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

This returns the list of key-value pairs in the dictionary, sorted by value from highest to lowest:

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

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

For the dictionary sorted by key, use the following:

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

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

The return is a list of tuples because dictionaries themselves can't be sorted.

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

This can be both printed or sent into further computation.

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

#2


1  

assuming your object is a list of tuples of dicts (closest interpretation I can reach via the data given), This would suffice:

假设你的对象是一个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  

Another method is below, maybe someone needs :

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

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  

If all you need is a list of keys ordered by Score value:

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

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'])

produces

产生

[2, 0, 1]

Otherwise, you can use an ordered dictionary

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

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

which gives you

给你的

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

that you can print out nicely

你可以很好地打印出来

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

10.0 xyz
80.0 dan
92.0 rob

#5


1  

I would just use:

我会用:

 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

then

然后

sorted(dict_items, comp)

For example for

例如

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

it gives:

它给:

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

But beware: your question title was about dictionnary items. The answer is coherent with the code in the question but only sort a list of tuples. If you really have a dict d, you should use sorted(d.items())

但要注意:你的问题标题是关于字典项目。答案与问题中的代码一致,但只对元组列表进行排序。如果你真的有一个dict d,你应该使用sorted(d.items())

#1


3  

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

This returns the list of key-value pairs in the dictionary, sorted by value from highest to lowest:

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

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

For the dictionary sorted by key, use the following:

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

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

The return is a list of tuples because dictionaries themselves can't be sorted.

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

This can be both printed or sent into further computation.

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

#2


1  

assuming your object is a list of tuples of dicts (closest interpretation I can reach via the data given), This would suffice:

假设你的对象是一个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  

Another method is below, maybe someone needs :

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

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  

If all you need is a list of keys ordered by Score value:

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

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'])

produces

产生

[2, 0, 1]

Otherwise, you can use an ordered dictionary

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

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

which gives you

给你的

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

that you can print out nicely

你可以很好地打印出来

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

10.0 xyz
80.0 dan
92.0 rob

#5


1  

I would just use:

我会用:

 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

then

然后

sorted(dict_items, comp)

For example for

例如

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

it gives:

它给:

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

But beware: your question title was about dictionnary items. The answer is coherent with the code in the question but only sort a list of tuples. If you really have a dict d, you should use sorted(d.items())

但要注意:你的问题标题是关于字典项目。答案与问题中的代码一致,但只对元组列表进行排序。如果你真的有一个dict d,你应该使用sorted(d.items())