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'}
]
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.
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.
In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With