Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reordering list of dicts arbitrarily in python

Tags:

python

list

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?

like image 393
chrism Avatar asked Dec 22 '22 01:12

chrism


1 Answers

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.

like image 60
Stephen Avatar answered Dec 26 '22 10:12

Stephen