简体   繁体   English

根据有序列表打印字典

[英]Print a dictionary based on an ordered list

I have sorted a dictionary based on a value within that dictionary. 我已经根据字典中的值对字典进行了排序。 Now, I want to print ordered, relevant aspects of the dictionary, using the sorted list of keys. 现在,我想使用键的排序列表来打印字典的有序相关部分。

Here's what I tried so far: 这是我到目前为止尝试过的:

sc = sorted(stats,key=lambda x:(stats[x]['avg length'],x)) #to get a sorted list of keys

for sc in stats:
    print "Name %s, Number: %s, Average length: %s, Max length: %s, Min length: %s" % (sc, stats[sc]["number"],stats[sc]["avg length"], stats[sc]["max length"], stats[sc]["min length"])

However, the order of the output does not match the order of my list sc. 但是,输出顺序与列表sc的顺序不匹配。 In fact, I cannot see any pattern with how the values outputted.. 实际上,我看不到任何有关如何输出值的模式。

Sorry if this is a trivial question--I'm new to python :( 抱歉,这是一个小问题-我是python的新手:(

At a guess, you probably meant to write something like: 大概,您可能打算编写类似以下内容的内容:

for s in sc:
    print "Name %s, Number: %s, Average length: %s, Max length: %s, Min length: %s" % (s, stats[s]["number"],stats[s]["avg length"], stats[s]["max length"], stats[s]["min length"])

You're replacing the sorted list in the existing for loop assignment. 您将替换现有for循环分配中的排序列表。

Your for loop is a little backwards. 您的for循环有点倒退。 You want to iterate over your ordered keys, not your original dictionary: 您想遍历订购的键,而不是原始字典:

for key in sc:
    print ... % (key, stats[key], ...

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

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