打印按值排序的字典 [英] Print a dict sorted by values

查看:165
本文介绍了打印按值排序的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在尝试遍历字典,然后将键/值从最大值打印到最小值.我一直在搜索此网站,很多人都在使用lambda,但我不确定它的工作方式,因此暂时不尝试使用它.

I'm basically trying to iterate through a dict and print out the key / values from largest value to lowest. I have been searching this site and a lot of people are using lambda but I'm not really sure how its working so I'm trying to avoid it for now.

dictIterator = iter(sorted(bigramDict.iteritems()))
for ngram, value in dictIterator:
    print("There are " + str(value) + " " + ngram)

查看上面的代码,我认为它将创建一个迭代器,该迭代器按从最大到最小的顺序返回键/值对,但不是.

Looking over the code above I assumed it would make an iterator which returns the key/value pairs in order from largest to smallest but it's not.

任何人都可以看到问题所在吗?或执行此操作的另一种方法?

Can anyone see what the problem is? or another method of doing this?

推荐答案

通过将第一个元素比第二个元素更重要,一个人可以利用对元组进行排序的事实:

One can take advantage of the fact that sort works on tuples by considering the first element as more important than the second etc:

d = { "a":4, "c":3, "b":12 }
d_view = [ (v,k) for k,v in d.iteritems() ]
d_view.sort(reverse=True) # natively sort tuples by first element
for v,k in d_view:
    print "%s: %d" % (k,v)

输出:

b: 12
a: 4
c: 3

单行生成器表达式:

sorted( ((v,k) for k,v in d.iteritems()), reverse=True)

输出:

[(12, 'b'), (4, 'a'), (3, 'c')]

这篇关于打印按值排序的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆