简体   繁体   中英

Sort the lists in a dictionary with lists as values

I have a program which produces the following:

{'Jim': [4, 2, 6], 'Fred': [5, 3, 8], 'Neil': [5, 1, 7]}

I would like to be able to sort the numbers in [] from highest to lowest.

eg

{'Jim': [6, 4, 2], 'Fred': [8, 5, 3], 'Neil': [7, 5, 1]}

I would then like to be able to display their name followed by their highest score, please could you tell me how to do this. I am coding in Python

Thanks

Use sorted function to do sorting. reverse=True should sort the data in reverse order ie, from highest to lowest.

>>> d = {'Jim': [4, 2, 6], 'Fred': [5, 3, 8], 'Neil': [5, 1, 7]}
>>> {i:sorted(j, reverse=True) for i,j in d.items()}
{'Jim': [6, 4, 2], 'Neil': [7, 5, 1], 'Fred': [8, 5, 3]}
>>> {i:max(j) for i,j in d.items()}
{'Jim': 6, 'Neil': 7, 'Fred': 8}

Use a dictionary comprehension and sorted .

>>> d = {'Jim': [4, 2, 6], 'Fred': [5, 3, 8], 'Neil': [5, 1, 7]}
>>> {k:sorted(d[k], reverse=True) for k in d}
{'Jim': [6, 4, 2], 'Neil': [7, 5, 1], 'Fred': [8, 5, 3]}

This will give you a new dictionary where the values (ie the lists) are sorted in descending order. If you want to sort the lists in place, use

>>> for k,v in d.iteritems():
...     d[k] = sorted(v, reverse=True)
... 
>>> d
{'Jim': [6, 4, 2], 'Neil': [7, 5, 1], 'Fred': [8, 5, 3]}

If you are using Python3, change d.iteritems() to d.items() .

I would then like to be able to display their name followed by their highest score, please could you tell me how to do this. I am coding in Python

Two options. If we assume d_sorted is your dictionary with the sorted lists, iterate over it and print the name and the first element of each list.

>>> for name, scores in d_sorted.iteritems():
...     print name, scores[0]
... 
'Jim', 6
'Neil', 7
'Fred', 8

But if that's all you want to do, a simpler way would be to use max and not pre-sort the lists at all. Assume that d is your original dictionary:

>>> for name, scores in d.iteritems():
...     print name, max(scores)
... 
'Jim', 6
'Neil', 7
'Fred', 8

Lists can be sorted inplace so unless you need a new dict you don't need to create one just call list.sort on each value/list:

d = {'Jim': [4, 2, 6], 'Fred': [5, 3, 8], 'Neil': [5, 1, 7]}
for sub in d.values():
  sub.sort(reverse=1)
print(d)
{'Neil': [7, 5, 1], 'Jim': [6, 4, 2], 'Fred': [8, 5, 3]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM