I have a list of 4 dicts (always 4) that look something like this:
[{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}]
I know exactly the order I want them in, which is:
2, 3, 1, 4
what's the simplest way of reordering them?
If it's always four, and you always know the order, just simply like this:
lst = [{...},{...},{...},{...}]
ordered = [lst[1],lst[2],lst[0],lst[3]]
If you meant to sort them by 'id', in that order:
ordered = sorted(lst, key=lambda d: [2,3,1,4].index(int(d['id'])))
Note that index()
is O(n)
but doesn't require you to build a dictionary. So for small inputs, this may actually be faster. In your case, there are four elements, ten comparisons are guaranteed. Using timeit
, this snippet runs 10% faster than the dictionary based solution by tokland... but it doesn't really matter since neither will likely be significant.
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