python - 如何按值对字典进行排序并返回格式化字符串列表?

标签 python list dictionary string-formatting

我有一个命令:

text_to_count = { "text1": 1, "text2":0, "text3":2}

我想通过对这个字典的值进行排序(降序)来创建一个格式化字符串列表。

即,我喜欢以下列表:

result = ["2 - text3", "1 - text1", "0 - text2"]

有什么想法吗?

编辑:

在等待回复的过程中,我一直在研究它并想出了:

result = map(lambda x: "{!s} - {!s}".format(x[1], x[0]), 
                       sorted(text_to_count.iteritems(), 
                       key = lambda(k, v): (v, k), reverse=True ))

不过我仍然有兴趣了解还有哪些其他解决方案,可能是更好的解决方案。

最佳答案

['%d - %s' % (v, k) for (k, v) in sorted(text_to_count.iteritems(),
    key=operator.itemgetter(1), reverse=True)]

关于python - 如何按值对字典进行排序并返回格式化字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4801344/

相关文章:

python - sympy lambdify : how to make more functions (NCDF, NPDF 等)可用

python - 列表与列表列表的第一个元素之间的交集

C# 为什么 List.Remove() 中断 'for loop' ?

LINQ - 组合多个列表以形成一个新列表并按键对齐?

c# - Kendo Grid 中的字典动态绑定(bind)

Java - 使用 Map/HashMap 将描述映射到单词

python - Django 中的智能查询,与用户的多对多关系

python - For Loop - Range - Python - 关于增量逻辑的问题

python - 是否存在某种倒置的if?在Python中

c# - 根据字典输入生成动态方程