如何在python中对字典进行排序

2024-10-03 09:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的问题。我知道了

{'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'}}

我必须先按性别排序,然后是事件和最后一次(PB-最快的第一次)


Tags: nameeventagegenderfsidleericpb
3条回答

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

不能对dict排序,因为标准字典是无序的。但是,您可以使用^{}

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

试试这个

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

你不能用Python对字典进行排序,它们天生就是无序的。在

但是,您可以sort the keys(),这将创建一个列表,然后使用该列表以伪有序的方式访问元素。在

相关问题 更多 >