蟒蛇按值排序字典项然后键
问题描述:
全部,蟒蛇按值排序字典项然后键
我很难按值排序字典,然后打印。
我对象(数据集)看起来像以下...
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)))
答
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)
返回是一个列表,因为字典本身不能进行排序。
这可以打印或发送到进一步的计算。
答
如果你需要的是按分数值排序键列表:
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
+0
会满足您的需求吗? – Pynchia
答
假设你的对象是的dicts
tuples
一个list
(我可以通过给出的数据达到最接近的解释),这样就足够了:
>>> 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'
})]
答
另一种方法是在下面的,也许有人需要:
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']))
答
我只想用:
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())
我们可以看到dataSet的内容吗? –
按分数排序,然后名称可能不会工作,除非你打算有可以排序名称的分数范围。 – SirParselot
@AyushShanker编辑,使之更明显。 –