Reputation: 1254
I have a list of objects look like below:
[{'id': 17L,
'price': 0,
'parent_count': 2},
{'id': 39L,
'price': 0,
'parent_count': 1},
{'id': 26L,
'price': 2.0,
'parent_count': 4},
{'id': 25L,
'price': 2.0,
'parent_count': 3}]
I want to sort the objects by 'parent_count'
in order to look like this:
[{'id': 39L,
'price': 0,
'parent_count': 1},
{'id': 17L,
'price': 0,
'parent_count': 2},
{'id': 25L,
'price': 2.0,
'parent_count': 3},
{'id': 26L,
'price': 2.0,
'parent_count': 4}]
Does anyone know a function?
Upvotes: 3
Views: 9936
Reputation: 8607
You can also do:
my_list.sort(key=lambda x: x.get('parent_count'))
which doesn't require operator.itemgetter
and doesn't cause an error if the key doesn't exist (those that don't have the key get put at the start).
Upvotes: 0
Reputation: 142126
Do you actually have "parent_say" and "parent_count"?
def get_parent(item):
return item.get('parent_count', item['parent_say'])
# return item.get('parent_count', item.get('parent_say')) if missing keys should just go to the front and not cause an exception
my_list.sort(key=get_parent)
or a bit more generic
def keygetter(obj, *keys, **kwargs):
sentinel = object()
default = kwargs.get('default', sentinel)
for key in keys:
value = obj.get(key, sentinel)
if value is not sentinel:
return value
if default is not sentinel:
return default
raise KeyError('No matching key found and no default specified')
Upvotes: 1
Reputation: 770
Also, you can use this method:
a = [{'id': 17L, 'price': 0, 'parent_count': 2}, {'id': 18L, 'price': 3, 'parent_count': 1}, {'id': 39L, 'price': 1, 'parent_count': 4}]
sorted(a, key=lambda o: o['parent_count'])
Result:
[{'parent_count': 1, 'price': 3, 'id': 18L}, {'parent_count': 2, 'price': 0, 'id': 17L}, {'parent_count': 4, 'price': 1, 'id': 39L}]
Upvotes: 3
Reputation: 601489
Use operator.itemgetter("parent_count")
as key
parameter to list.sort()
:
from operator import itemgetter
my_list.sort(key=itemgetter("parent_count"))
Upvotes: 12