Dario Bani
Dario Bani

Reputation: 123

Reorder dictionaries within a list

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?

Upvotes: 0

Views: 54

Answers (3)

cottontail
cottontail

Reputation: 23321

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

Upvotes: 3

tlentali
tlentali

Reputation: 3455

@not_a_robot answered it already, just to give you an alternative answer, you can use the sorted function like so :

new_list = sorted(your_list, key=lambda d: d['market_share'], reverse=True) 

Upvotes: 1

Badr B
Badr B

Reputation: 1413

You can use the sorted() function and specify things like the key argument (what value to sort by) and the reverse argument (whether to sort descending or ascending). In this case, you want to sort by dictionary['market_share'] so key=lambda dictionary:dictionary['market_share']. You also want to sort by decreasing market share, so reverse=True. All of this together gives

data = [{'isin': 'IE000000001', 'MP': 'B', 'market_share': 30}, {'isin': 'IE000000002', 'MP': 'C', 'market_share': 50}, {'isin': 'IE000000003', 'MP': 'D', 'market_share': 70}]
data = sorted(data, key=lambda dictionary: dictionary['market_share'], reverse=True)

Upvotes: 1

Related Questions