Home > front end >  Reorder dictionaries within a list
Reorder dictionaries within a list

Time:05-23

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?

CodePudding user response:

You don't need pandas for this.

# sort the list by market_share
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}]

CodePudding user response:

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)

CodePudding user response:

@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) 
  • Related