Sorting dicts inside dicts

Eli Bendersky eliben at gmail.com
Sat Jul 3 06:13:06 EDT 2010


On Sat, Jul 3, 2010 at 03:34, MRAB <python at mrabarnett.plus.com> wrote:

> abhijeet thatte wrote:
>
>> Hi,
>> I have a huge dict structure like below:
>>
>> /*{'module':{'reg_dict_0':{'name':'abc','reg_addr':'2004'},'reg_dict_1':{'name':'xyz','reg_addr':'2002'},'reg_dict_2':{'name':'pqr','reg_addr':'2008'}}*/
>>
>> Module dict and reg_dicts contain many elements than shown.
>> I want to sort this 'module' dictionary as per 'reg_addr' element in every
>> 'reg_dict'.
>> There is no relation between 'reg_dict' suffix and address. So, reg_dict_0
>> can contain reg_address = 2000/72 (any number)
>> I do not want output in a list format as the actual dict size is huge
>> which I want to use based on key value pair.
>>
>> So, I want output as :
>>
>>
>> /*{'module':{'reg_dict_1':{'name':'xyz','reg_addr':'2002'},'reg_dict_0':{'name':'abc','reg_addr':'2004'},'reg_dict_2':{'name':'pqr','reg_addr':'2008'}}*/
>> /*
>> */
>>
>> Is it possible to sort the things? What I guess is Python stores dicts in
>> a tree like structure but I am forcing it to store the way I want. Is it
>> possible  to do something like that.
>>
>>  Python dicts are implemented as hash tables, not trees, for speed, and
> they are unordered.
>
> If the order matters then you should use an ordered dict instead. You
> should be able to find an implementation of one.
>
> The easiest way to find such an implementation is in the standard library
of Python, starting with Python 3.1 (collections.OrderedDict)

Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100703/a2b5df14/attachment-0001.html>


More information about the Python-list mailing list