0

I have the following data structure (coming from a piece of code I can't modify):

{
 'key2':[{'name':'Oliver','value':1}, {'name':'Rambo','value':2}],
 'key1':[{'name':'Robert','value':4}, {'name':'Rambo','value':0}],
 'Ali':[{'name':'Oliver','value':1}, {'name':'Robert','value':0}]
}

I want to sort this list by 'key name' and not by key value. So if I apply a sort on the previous list the output should be:

{
 'Ali':[{'name':'Oliver','value':1}, {'name':'Robert','value':0}],
 'key1':[{'name':'Robert','value':4}, {'name':'Rambo','value':0}],
 'key2':[{'name':'Oliver','value':1}, {'name':'Rambo','value':2}]
}

I found a lot of litterature about how sorting by key value, but almost nothing regarding sorting by key name. What is the most efficient method to do that?

Alex Grs
  • 3,231
  • 5
  • 39
  • 58
  • There is no such thing as a 'key name', and it is unclear to me how you understand the concept. There is another problem here: Dictionaries are not ordered, you cannot sort them. – Martijn Pieters Sep 15 '14 at 09:14
  • You can enumerate the keys and / or values and sort that enumeration, but I still don't know how your output is sorted. On the value associated with the `name` key found in the last dictionary from the value perhaps? – Martijn Pieters Sep 15 '14 at 09:14
  • Well, I mean I want to sort it key attribute name : 'Ali', 'key1' ,'key2' ... I was thinking converting it to a list and then using sorted() on it. But I can't figure out how. Because here, the attribute name is the data I want to sort. – Alex Grs Sep 15 '14 at 09:15
  • In any case, any of the 'sort dictionary by value' questions here on SO should provide you with an answer, like [Sort a Python dictionary by value](http://stackoverflow.com/q/613183). You need to provide a sort key function that'll return the think you want to sort on. – Martijn Pieters Sep 15 '14 at 09:16
  • Ah, so you are sorting by *key* then. That's just the key, not a 'key name'. – Martijn Pieters Sep 15 '14 at 09:16
  • You change the representation of the dictionary to sort it, but then the output will not be like you said. Your output is a dictionary, and dictionaries are not ordered. – Juan Cespedes Sep 15 '14 at 09:17
  • If you want to know why dictionaries are listed like that: https://www.youtube.com/watch?v=C4Kc8xzcA68 – eSedano Sep 15 '14 at 09:17
  • you could take a look at the sorted containers library : https://pypi.python.org/pypi/sortedcontainers/0.6.0 [I'm not affiliated to the sorted container library in any way] – Arthur Vaïsse Sep 15 '14 at 12:33

0 Answers0