反转字典并显示值 [英] To reverse a dictionary and display values

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

问题描述

我想反转字典并以特定格式显示.这是示例输入:

I want to reverse a dictionary and display it in a specific format. Here is the sample input:

{'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900} 

输出应为:

这是我使用代码的地方,但是问题在于它返回的是列表而不是字典.

This is where I am with the code, but the problem is that it returns a list and not a dictionary.

代码:

def formatted_print(my_dict):
    d = my_dict
    c = sorted(d.items(), cmp=lambda a,b: cmp(a[1], b[1]), reverse=True)
    return (c)

推荐答案

简单代码,无需导入任何模块或库:

Simple code without importing any module or library :

def formatted_print(D):
    list_tuples=sorted(D.items(), key=lambda x: (-x[1], x[0]))

    for items in list_tuples:
        x="{0:10s}{1:6.2f}".format(items[0],items[1])
        print(x)

它打印:

alex       90.55
eva        88.50
tim        65.90
john       34.48

这篇关于反转字典并显示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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