Python dictionaries dictionary sort

I have a dictionary with dictionaries like

d = {
  'hain': {'facet': 1, 'wrapp': 1, 'chinoiserie': 1}, 
  'library': {'sconc': 1, 'floor': 1, 'wall': 2, 'lamp': 6, 'desk': 1, 'table': 1, 'maine': 1} 
}

So, I want to change the sorting of this dictionary based on the final value:

so I expect to print something like this:

  key_1,   key_2 , value
 library   lamp      6
 library   wall      2

etc.

How do i get this?

thanks

0
source share
3 answers

Here's how you can get the sorted list you are looking for:

items = ((k, k2, v) for k in d for k2, v in d[k].items())
ordered = sorted(items, key=lambda x: x[-1], reverse=True)

This first converts your dictionary into a generator that gives tuples (key_1, key_2, value), and then sorts it based on value. reverse=Truemakes sorting the highest to the lowest.

Here is the result:

>>> pprint.pprint(ordered)
[('library', 'lamp', 6),
 ('library', 'wall', 2),
 ('hain', 'facet', 1),
 ('hain', 'wrapp', 1),
 ('hain', 'chinoiserie', 1),
 ('library', 'sconc', 1),
 ('library', 'floor', 1),
 ('library', 'desk', 1),
 ('library', 'table', 1),
 ('library', 'maine', 1)]

, , ( , key_1), , - , .

, :

for key_1, key_2, value in ordered:
    print key_1, key2, value         # add whatever formatting you want to here
+6

, value, , key, key_2:

dout={}
for e in d:
    for es in d[e]:
        lineOut='%s %s %i' % (e, es, d[e][es])
        key= d[e][es]
        dout.setdefault(key, []).append(lineOut)  

for e in sorted(dout, reverse=True):
    for ea in sorted(dout[e], reverse=False):
        print ea         

:

library lamp 6
library wall 2
hain chinoiserie 1
hain facet 1
hain wrapp 1
library desk 1
library floor 1
library maine 1
library sconc 1
library table 1
+1

I'm not sure exactly how you want to sort the result, but this should get you started:

>>> for key in d:
        for key2 in d[key]:
            print key, key2, d[key][key2]
0
source

All Articles