Xiaobo Li Xiaobo Li - 6 months ago 40
Python Question

How to sort multiple dicts in list with key (google babyname exercise_modified)

This is a modified list I created from google babyname exercise.

[
[{'year': 1998}, {'rank': 1, 'boy': 'pic', 'girl': 'Emy'}, {'rank': 2,
'boy': 'badf', 'girl': 'Hdf'}, ...{'rank': 1000, 'boy': 'Jal', 'girl':
'Sky'}],
[{'year': 1999}, {'rank': 1, 'boy': 'xic', 'girl': 'Ely'}, {'rank': 2,
'boy': 'aacb', 'girl': 'Hah'}, ...{'rank': 1000, 'boy': 'Jal', 'girl':
'Sky'}],
[{'year': 1958}, {'rank': 1, 'boy': 'Mic', 'girl': 'Emy'}, {'rank': 2,
'boy': 'caob', 'girl': 'Han'}, ...{'rank': 1000, 'boy': 'Jal', 'girl':
'Sky'}],
....
]


How to sort this list with different keys? such as year, rank....

Wen Wen
Answer Source

I convert the list dict to pandas DataFrame which make sort become easier

LIST=[[{'year': 1998}, {'rank': 1, 'boy': 'pic', 'girl': 'Emy'}, {'rank': 2,
'boy': 'badf', 'girl': 'Hdf'},{'rank': 1000, 'boy': 'Jal', 'girl':
'Sky'}],
[{'year': 1999}, {'rank': 1, 'boy': 'xic', 'girl': 'Ely'}, {'rank': 2,
'boy': 'aacb', 'girl': 'Hah'},{'rank': 1000, 'boy': 'Jal', 'girl':
'Sky'}],
[{'year': 1958}, {'rank': 1, 'boy': 'Mic', 'girl': 'Emy'}, {'rank': 2,'boy': 'caob', 'girl': 'Han'},{'rank': 1000, 'boy': 'Jal', 'girl':'Sky'}]]
DFLIST=[]
for A in LIST:
    DFLIST.append(pd.DataFrame(A).ffill().dropna())
NEWDF=pd.concat(DFLIST,axis=0).reset_index(drop=True)

Out[540]: 
    boy girl    rank    year
0   pic  Emy     1.0  1998.0
1  badf  Hdf     2.0  1998.0
2   Jal  Sky  1000.0  1998.0
3   xic  Ely     1.0  1999.0
4  aacb  Hah     2.0  1999.0
5   Jal  Sky  1000.0  1999.0
6   Mic  Emy     1.0  1958.0
7  caob  Han     2.0  1958.0
8   Jal  Sky  1000.0  1958.0

For Example : sort by rank

NEWDF.sort_values(['year','rank'],ascending=[True,False])


Out[542]: 
    boy girl    rank    year
8   Jal  Sky  1000.0  1958.0
7  caob  Han     2.0  1958.0
6   Mic  Emy     1.0  1958.0
2   Jal  Sky  1000.0  1998.0
1  badf  Hdf     2.0  1998.0
0   pic  Emy     1.0  1998.0
5   Jal  Sky  1000.0  1999.0
4  aacb  Hah     2.0  1999.0
3   xic  Ely     1.0  1999.0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download