Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dict by sub-value in Python

I spent some time reading on SOF and am having issues solving this problem. I cannot seem to find how to get the following data structure sorted by the sub-value:

data = {}
data[1] = {name: "Bob", ...}
data[2] = {name: "Carl", ...}
data[3] = {nane: "Alice", ...}

I need to get this data into some form of a list/tuple/order dict structure which is alphabetized so that the final result is something like this:

finalData = [{name: "Alice", ...}, {name: "Bob", ...}, {name: "Carl", ...}]

Thanks.

like image 568
MasterGberry Avatar asked Oct 21 '25 04:10

MasterGberry


1 Answers

Do you mean something like

sorted(data.values(), key=itemgetter(name))

>>> from operator import itemgetter
>>> data = {}
>>> name = 'name'
>>> 
>>> data[1] = {name: "Bob"}
>>> data[2] = {name: "Carl"}
>>> data[3] = {name: "Alice"}
>>>
>>> sorted(data.values(), key=itemgetter(name))
[{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carl'}]
like image 178
arshajii Avatar answered Oct 23 '25 18:10

arshajii