Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}
  ]
like image 366
Hyperion Avatar asked Feb 21 '17 10:02

Hyperion


People also ask

How do you move an element to the end of a list in Python?

To move an element to the end of a list: Use the list. append() method to append the value to the end of the list. Use the del statement to delete the original element from the list.

How do you move a list element in Python?

Method : Using pop() + insert() + index() This particular task can be performed using combination of above functions. In this we just use the property of pop function to return and remove element and insert it to the specific position of other list using index function.

Can you nest a dictionary in a list Python?

In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.


1 Answers

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'}]
like image 93
Ashwini Chaudhary Avatar answered Nov 14 '22 22:11

Ashwini Chaudhary