Python_newbie
Python_newbie

Reputation: 203

Custom sort a list of ordered dict by fixing one of the key's values as first element

I have a list of ordereddict

[OrderedDict([('song', 'Hoses'), ('lyric', 'crea'), ('Music', 'reut'), ('BGM', 'DJU'),  ('Totalsecs', 223.457894215)])
,OrderedDict([('song', 'Goses'), ('lyric', 'recrea'), ('Music', 'reutser'), ('BGM', 'DJS'),  ('Totalsecs', 158.514553868968)])
,OrderedDict([('song', 'reoses'), ('lyric', 'arecrea'), ('Music', 'hiureut'), ('BGM', 'VJU'),  ('Totalsecs', 11.879461215421)])
,OrderedDict([('song', 'reteoses'), ('lyric', 'makuri'), ('Music', 'reut'), ('BGM', 'DJU'),  ('Totalsecs', 123.513353868968)]
)]

i want to sort them based on the totalsecs key by fixing first element, i.e in the above list of ordereddict, i want to fix ('Totalsecs', 158.514553868968) as the first element so that the rest of them are sorted below that so the list of ordered dict will become

[OrderedDict([('song', 'Goses'), ('lyric', 'recrea'), ('Music', 'reutser'), ('BGM', 'DJS'),  ('Totalsecs', 158.514553868968)])
 ,OrderedDict([('song', 'Hoses'), ('lyric', 'crea'), ('Music', 'reut'), ('BGM', 'DJU'),  ('Totalsecs', 223.457894215)])
,OrderedDict([('song', 'reoses'), ('lyric', 'arecrea'), ('Music', 'hiureut'), ('BGM', 'VJU'),  ('Totalsecs', 11.879461215421)])
,OrderedDict([('song', 'reteoses'), ('lyric', 'makuri'), ('Music', 'reut'), ('BGM', 'DJU'),  ('Totalsecs', 123.513353868968)]
)]

basically I want to fix the first element and the rest should be in sorted order, if there is a number that is lesser than the first element is found it should not go before first element. Do we have any built in function for this in python? I have asked a similar kind of question for lists, but this if for list of ordereddict

Upvotes: 0

Views: 217

Answers (1)

jpp
jpp

Reputation: 164753

One way is to perform your two sorts separately and then combine.

Given a list A of OrderedDict objects:

from operator import itemgetter

# retrieve threshold
threshold = A[1]['Totalsecs']

# sort above threshold
sort1 = sorted((i for i in A if i['Totalsecs'] >= threshold), key=itemgetter('Totalsecs'))

# sort below threshold
sort2 = sorted((i for i in A if i['Totalsecs'] < threshold), key=itemgetter('Totalsecs'))

# combine into one list
res = sort1 + sort2

print(res)

[OrderedDict([('song', 'Goses'), ('lyric', 'recrea'), ('Music', 'reutser'),
              ('BGM', 'DJS'), ('Totalsecs', 158.514553868968)]),
 OrderedDict([('song', 'Hoses'), ('lyric', 'crea'), ('Music', 'reut'),
              ('BGM', 'DJU'), ('Totalsecs', 223.457894215)]),
 OrderedDict([('song', 'reoses'), ('lyric', 'arecrea'), ('Music', 'hiureut'),
              ('BGM', 'VJU'), ('Totalsecs', 11.879461215421)]),
 OrderedDict([('song', 'reteoses'), ('lyric', 'makuri'), ('Music', 'reut'),
              ('BGM', 'DJU'), ('Totalsecs', 123.513353868968)])]

Upvotes: 1

Related Questions