Sorting and deleting dictionaries

I am stuck with dictionaries and sorting in python, I have the following values ​​stored in a dictionary:

{'PersonA': 87.0, 'PersonB': 89.0, 'PersonC': 101, 'PersonD': 94, 'PersonE': 112}

      

I want to:

1) Sort them so that they are ordered by highest score first, down to lowest score
2) Remove grades from the dictionary, leaving only names

For example, in the above example, the function should return:

['PersonE', 'PersonC', 'PersonD', 'PersonB', 'PersonA']

      

+3


source to share


4 answers


You can do it easily with sorted

:

>>> d = {'PersonA': 87.0, 'PersonB': 89.0, 'PersonC': 101, 'PersonD': 94, 'PersonE': 112}
>>> sorted(d, key=d.get, reverse=True)
['PersonE', 'PersonC', 'PersonD', 'PersonB', 'PersonA']
>>>

      



Note that the output is a list of names. You cannot sort a dictionary or collection in Python because they are both naturally unordered.

+7


source


You can do the following:

d1 = {'PersonA': 87.0, 'PersonB': 89.0, 'PersonC': 101, 'PersonD': 94, 'PersonE': 112}
print([n for n,s in sorted(d1.items(), key=lambda v:v[1], reverse=True)])

      



Result:

['PersonE', 'PersonC', 'PersonD', 'PersonB', 'PersonA']

      

+2


source


It is not possible to sort the dictionary because the dictionary has no order, but other types such as lists and tuples are not. But you can have a sorted view.

For example,

import operator
x = {first: 2, second: 4, third:3, fourth:1, fifth:0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

      

or you can also do

sorted(x.values()) to get a sorted representation.

      

0


source


Ability to save dick and sort it:

>>>from collections import OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

      

Detail: sorted has a reverse (bool) arg, for example:

>>> OrderedDict(sorted(d.items(), key=lambda t: t[0], reverse = True))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

      

Common usage:

>>> dic = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
>>> dic['banana']
3

      

font: https://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

0


source







All Articles