Reputation: 1
I have a list of dictionaries:
[{"id":1,"value":"p1","num":2},{"id":2,"value":"p1","num":4},{"id":3,"value":"p2","num":4}]
I want to iterate this list by only having id and create a list based on first picking up p1 and then p2, if p1 is in multiple , then giving priority to the higher number
out = [2,1,3]
How do I do it in one loop?
Upvotes: 0
Views: 416
Reputation: 54193
Well there's no way to do this in only one loop, since your sorting is custom. You have to at least sort it first.
def sort_function(d):
value_str, num = d['value'], d['num']
# This assumes that 'p2' should sort before 'p12'
value = int(value_str[1:]) # strips off the 'p' and treats the rest as a number
return (value, -num)
out = [dct['id'] for dct in sorted(input_dictionary, key=sort_function)]
Upvotes: 2