⇤ ← Revision 1 as of 2003-11-21 19:31:10
Size: 526
Comment: sorting by converting to (key,dict), then sorting, then converting back to dict
|
Size: 579
Comment: Question: This a good way?
|
Deletions are marked like this. | Additions are marked like this. |
Line 26: | Line 26: |
== Questions == This a good way? -- LionKimbro |
Sorting Lists of Dictionaries
Frequently you want to sort a list of dictionaries, based on some particular key.
For example:
Toggle line numbers
1 a = { "key1":5, "key2":8, "key3":2 }
2 b = { "key1":7, "key2":4, "key3":9 }
3 c = { "key1":6, "key2":1, "key3":1 }
4 l = [ a,b,c ] # how do you sort this list?
There are many ways to do this; Here's one way I've been doing it:
Toggle line numbers
1 sort_key = "key2"
2 l = [(d[sort_key],d) for d in l]
3 l.sort()
4 l = [d for (k,d) in l]
Questions
This a good way? -- LionKimbro