Hyperion
Hyperion

Reputation: 2625

Python - Move elements in a list of dictionaries to the end of the list

I've a list of dictionaries like this:

lst = [
  {'id': 1, 'language': 'it'},
  {'id': 2, 'language': 'en'},
  {'id': 3, 'language': 'es'},
  {'id': 4, 'language': 'en'}
  ]

I want to move every dictionary that has language != 'en' to the end of the list while keeping the order of other of results. So the list should look like:

lst = [ 
  {'id': 2, 'language': 'en'},
  {'id': 4, 'language': 'en'},
  {'id': 1, 'language': 'it'},
  {'id': 3, 'language': 'es'}
  ]

Upvotes: 8

Views: 2544

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

Use sorting. Idea is to sort on whether is equal to 'language' or not. If language is equal to 'en' then key function will return False else True (False < True). As Python's sort is stable the order will be preserved.

>>> sorted(lst, key=lambda x: x['language'] != 'en')
[{'id': 2, 'language': 'en'},
 {'id': 4, 'language': 'en'},
 {'id': 1, 'language': 'it'},
 {'id': 3, 'language': 'es'}]

Upvotes: 15

Related Questions