简体   繁体   English

在Python中用内部字典中的值对字典进行排序

[英]Sorting a dict by values inside an inner dict in Python

My apologies if I am using the incorrect terminology, as I'm a bit of a Python n00b when it comes to the proper descriptions for data structures. 如果我使用的是不正确的术语,我很抱歉,因为当涉及到数据结构的正确描述时,我有点像Python n00b。

I have a data structure that looks like this: 我有一个如下所示的数据结构:

{
    u'COU': {'hl': 39, 'hw': 42, 'winPct': Decimal('0.5471698113207547169811320755'), 'al': 36, 'l': 72, 'w': 87, 'aw': 45}, 
    u'MIN': {'hl': 42, 'hw': 39, 'winPct': Decimal('0.3559322033898305084745762712'), 'al': 57, 'l': 114, 'w': 63, 'aw': 24}, 
    u'BOW': {'hl': 36, 'hw': 44, 'winPct': Decimal('0.5432098765432098765432098765'), 'al': 37, 'l': 74, 'w': 88, 'aw': 44}
}

I want to sort this data structure by the value in winPct inside the inner dict and searching online has revealed a dazzling array of advice that makes no sense to this raised-on-PHP developer. 我希望通过内部字典中的winPct中的值对这个数据结构进行排序,并且在线搜索已经发现了一系列令人眼花缭乱的建议,这对于这个基于PHP的开发人员来说毫无意义。

Thanks in advance for your help. 在此先感谢您的帮助。

You can't sort a dictionary, but you could convert the dictionary into a list of tuples with the form (key, value) . 您无法对字典进行排序,但您可以将字典转换为具有表单(key, value)的元组列表。

sorted_d = sorted(d.iteritems(), key=lambda v: v[1]['winPct'])

To Reverse the sorting as per your comment use: 要根据您的评论使用反转排序:

sorted_d = sorted(d.iteritems(), key=lambda v: v[1]['winPct'], reverse=True)

Your data structure is a dictionary, and dictionaries don't have an ordering on the associations inside them, so I'm going to interpret "sort this data structure" to mean "make a list containing the (key,values) pairs from this data structure". 你的数据结构是一个字典,字典对它们内部的关联没有排序,所以我要解释“将这个数据结构排序”来表示“从中创建包含(键,值)对的列表”数据结构”。 This may or may not be what you want. 这可能是也可能不是你想要的。 So, first of all, get those pairs: 所以,首先,得到那些对:

pairs = d.items()

(note: this returns a list in Python 2; I think it returns something else in Python 3, for which you'd need to call list() explicitly to make it into something you could sort, or call sorted instead of sort ). (注意:这会在Python 2中返回一个列表;我认为它会在Python 3中返回其他内容,为此您需要显式调用list()以使其成为可以排序的内容,或者调用sorted而不是sort )。 Now sort according to your criterion: 现在根据您的标准排序:

pairs.sort(key = lambda (k,v): v['winPct'])

and now pairs contains what (perhaps) you want. 现在pairs包含你想要的(也许)。

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

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