我有一本字典词典如下:
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
我想为字典(ls)的每个键选择k个最大值及其键。我写了下面的命令。它只给了我没有值的k个最大的键。
Python代码:
import heapq
k=2
for dic in ls:
for key in dic:
print(heapq.nlargest(k, dic[key], key=dic[key].get))
输出
['2', '3']
['3', '1']
我需要拥有每个选定键的值。
答案 0 :(得分:3)
首先,我只是想检查你为什么
<xsl:variable name='_LoopVar_102_0_set' select="$_ManageWorkOrderSubmitWorkOrderRequest/soapenv:Envelope[1]/soapenv:Body[1]/bons1:ManageWorkOrderSubmitWorkOrderRequest[1]/WorkOrder[1]/CustomerAccount[1]/ServiceAddress[1]/LineCardInfo[1]/Cable"/>
<xsl:variable name='_LoopVar_102_1_set' select="$_LoopVar_100_0/Cable"/>
<xsl:variable name='_SetMax42r'>
<xsl:choose>
<xsl:when test="count($_LoopVar_102_0_set) >= count($_LoopVar_102_1_set)">
<xsl:apply-templates select="$_LoopVar_102_0_set" mode='enumerate'/>
</xsl:when>
<xsl:when test="count($_LoopVar_102_1_set) >= count($_LoopVar_102_0_set)">
<xsl:apply-templates select="$_LoopVar_102_1_set" mode='enumerate'/>
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:variable name='_SetMax42' select="$_SetMax42r/*"/>
<xsl:variable name='count2'>
<xsl:choose>
<xsl:when test='count(_SetMax42) = 0'>
<xsl:value-of select="1"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select='count(_SetMax42)'/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:for-each select="1 to $count2">
<xsl:variable name="_index43" select='$count2'/>
<xsl:variable name='_LoopVar_102_0' select="$_LoopVar_102_0_set[position()=$_index43]"/>
<xsl:variable name='_LoopVar_102_1' select="$_LoopVar_102_1_set[position()=$_index43]"/>
这是一个包含字典的列表,与您在问题中的描述不符。
这是一个使用dict理解的解决方案,可以提供你想要的东西:)
=ArrayFormula(SUM(VALUE(RIGHT(K4:K29,2))))
这里用于解决您的问题:
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
答案 1 :(得分:1)
怎么样:
from operator import itemgetter
for d in ls:
for key, d2 in d.items():
print(dict(heapq.nlargest(k, d2.items(), key=itemgetter(1))))
请注意,您的值仍然是字符串,因此它们是按词汇排序的,这不是您想要的,因为'2' > 12'
和字典不订购!