0

I have a dictionary of dictionaries like the following

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 reverse sort this dictionary based on the ultimate value:

so what I am expecting is to print out something like this:

  key_1,   key_2 , value
 library   lamp      6
 library   wall      2

and so on...

How do i get this?

Thanks

4

3 回答 3

6

Here is how you could 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 yields the tuples (key_1, key_2, value), and then sorts this based on the value. The reverse=True makes it sort highest to 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)]

Note that when the values match exactly, the order is arbitrary (except that items will always be grouped by key_1), if you would like some other behavior just edit your question with what you expect in these scenarios.

After obtaining this list, you could print it out by iterating over it like this:

for key_1, key_2, value in ordered:
    print key_1, key2, value         # add whatever formatting you want to here
于 2012-05-14T23:57:29.103 回答
1

If you want it sorted first be reverse sorted by value then ascending sorted by key then 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         

prints:

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
于 2012-05-15T00:10:17.670 回答
0

I'm not sure exactly how you want the output sorted, but this should get you started:

>>> for key in d:
        for key2 in d[key]:
            print key, key2, d[key][key2]
于 2012-05-14T23:55:47.830 回答