3

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.

MasterGberry
  • 2,800
  • 6
  • 37
  • 56
  • You're mixing and matching your container types. A `list` uses numerical indices and is ordered / can be sorted. A `dict` is a key-value store which is inherently unordered. You can generate a sorted representation of the data in a `dict`, but the `dict` itself will remain unsorted. You could also look into `OrderedDict`. – g.d.d.c Aug 22 '13 at 15:24
  • If you had a list of these dictionaries (which seems to make more sense), you'd need something like `data.sort(key=operator.itemgetter("name"))`. – Sven Marnach Aug 22 '13 at 15:30
  • possible duplicate of [Python: Sort a dictionary by value](http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) – Marcin Aug 22 '13 at 15:30

1 Answers1

6

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'}]
arshajii
  • 127,459
  • 24
  • 238
  • 287