I have a list containing dictionaries that looks like this:
[
{'isin': 'IE000000001', 'MP': 'B', 'market_share': 30},
{'isin': 'IE000000002', 'MP': 'C', 'market_share': 50},
{'isin': 'IE000000003', 'MP': 'D', 'market_share': 70}
]
I would like to reorder the dictionaries in my list based on their 'market share' so that I would end up with something like that
[
{'isin': 'IE000000003', 'MP': 'D', 'market_share': 70},
{'isin': 'IE000000002', 'MP': 'C', 'market_share': 50},
{'isin': 'IE000000001', 'MP': 'B', 'market_share': 30}
]
Do you have any recommendations?
Given you have a list of dictionaries where each dictionary has the "market_share"
key by which you want the list sorted, simply call .sort
on the list and use a sorting key that uses the market share value.
my_data.sort(key=lambda x:x['market_share'], reverse=True)
my_data
[{'isin': 'IE000000003', 'MP': 'D', 'market_share': 70},
{'isin': 'IE000000002', 'MP': 'C', 'market_share': 50},
{'isin': 'IE000000001', 'MP': 'B', 'market_share': 30}]