简体   繁体   English

排序字典python字典

[英]Sort a dictionary of dictionaries python

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 谢谢

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. 这首先将您的字典转换为生成元组(key_1, key_2, value)的生成器,然后根据该值对其进行排序。 The reverse=True makes it sort highest to lowest. reverse=True使它从高到低排序。

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. 请注意,当值完全匹配时,顺序是任意的(除非项目始终按key_1分组),如果您想要其他行为,只需使用在这些情况下的期望编辑问题即可。

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

If you want it sorted first be reverse sorted by value then ascending sorted by key then key_2 : 如果要先按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         

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

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM