2

All,

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

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

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.

entries = sorted([(dataSet[entry]['studentName'], dataSet[entry]['Score']) for entry in dataSet]) for name, score in entries: print(('Student: {} -- Score: {}%'.format(name, score))) 
5
  • can we see the contents of dataSet? Commented Dec 8, 2015 at 13:15
  • Sorting by score and then names probably isn't going to work unless you are going to have ranges of scores that you can sort the names in. Commented Dec 8, 2015 at 13:15
  • @AyushShanker edited to make that more obvious. Commented Dec 8, 2015 at 13:16
  • @SirParselot Thinking about it, I am happy by simply sorting by Score. Python is not my domain and beggars can't be choosers! Commented Dec 8, 2015 at 13:20
  • 1
    It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples. Commented Dec 8, 2015 at 13:23

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

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

Comments

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 

1 Comment

would this suit your needs?
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())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.