Adriano
Adriano

Reputation: 9

how to sort a dictionary in a dictionary in python

Here is my problem. I got this

{'Ciaran Johnson': {'PB': 58.2,
                    'Gender': 'M',
                    'Age': 6,
                    'Event': 'IM',
                    'Name': 'Ciaran Johnson'},
 'Joan Pine': {'PB': 44.0,
               'Gender': 'F',
               'Age': 6,
               'Event': 'FS',
               'Name': 'Joan Pine'},
 'Eric Idle': {'PB': 57.2,
               'Gender': 'M',
               'Age': 6,
               'Event': 'IM',
               'Name': 'Eric Idle'},
 'Kirsty Laing': {'PB': 58.2,
                  'Gender': 'F',
                  'Age': 6,
                  'Event': 'IM',
                  'Name': 'Kirsty Laing'}}

and I have to sort it firsty by gender,then event and lastle time(PB -the fastest to be first)

Upvotes: 0

Views: 457

Answers (3)

NPE
NPE

Reputation: 500227

I have this [dict] and I have to sort it...

You cannot sort a dict, since standard dictionaries are unordered. You can, however, use an OrderedDict:

In [2]: from collections import OrderedDict

In [3]: sd = OrderedDict(sorted(d.items(), key=lambda (k,v): (v['Gender'], v['Event'], v['PB'])))

In [4]: sd
Out[4]: OrderedDict([('Joan Pine', {'PB': 44.0, 'Gender': 'F', 'Age': 6, 'Event': 'FS', 'Name': 'Joan Pine'}), ('Kirsty Laing', {'PB': 58.2, 'Gender': 'F', 'Age': 6, 'Event': 'IM', 'Name': 'Kirsty Laing'}), ('Eric Idle', {'PB': 57.2, 'Gender': 'M', 'Age': 6, 'Event': 'IM', 'Name': 'Eric Idle'}), ('Ciaran Johnson', {'PB': 58.2, 'Gender': 'M', 'Age': 6, 'Event': 'IM', 'Name': 'Ciaran Johnson'})])

Upvotes: 3

Abhijit
Abhijit

Reputation: 63707

Try this

>>> for k,v in sorted(spam.items(),key=lambda k:(k[1]['Gender'],k[1]['Age'],k[1]['PB'])):
    print(k,v)


Joan Pine {'PB': 44.0, 'Gender': 'F', 'Age': 6, 'Event': 'FS', 'Name': 'Joan Pine'}
Kirsty Laing {'PB': 58.2, 'Gender': 'F', 'Age': 6, 'Event': 'IM', 'Name': 'Kirsty Laing'}
Eric Idle {'PB': 57.2, 'Gender': 'M', 'Age': 6, 'Event': 'IM', 'Name': 'Eric Idle'}
Ciaran Johnson {'PB': 58.2, 'Gender': 'M', 'Age': 6, 'Event': 'IM', 'Name': 'Ciaran Johnson'}
>>> 

Upvotes: 0

Ali Afshar
Ali Afshar

Reputation: 41633

You can't sort a dictionary in Python, they are inherently unordered.

You can sort the keys() though, which creates a list, and then use that list to access the elements in a fake ordered way.

Upvotes: 2

Related Questions