从特定格式的字典打印值和键(python) [英] printing values and keys from a dictionary in a specific format (python)

查看:178
本文介绍了从特定格式的字典打印值和键(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字典(姓名和成绩):

I have this dictionary (name and grade):

d1 = {'a': 1, 'b': 2, 'c': 3}

我必须像这样打印:

|a          | 1          |       C |
|b          | 2          |       B |
|c          | 3          |       A |

我创建了一个新字典,以便根据这些条件查找信件分级:

I created a new dictionary to find out the letter grading based on these conditions:

d2 = {}
d2 = d1
for (key, i) in d2.items():
    if i = 1:
        d2[key] = 'A'
    elif i = 2:
        d2[key] = 'B'
    elif i = 3:
        d2[key] = 'C'

尝试使用以下代码打印时: / p>

When trying to print it using the following code:

sorted_d = sorted(d)

format_str = '{:10s} | {:10f} | {:>7.2s} |'
for name in sorted_d:
    print(format_str.format(name, d[name]))

打印:

a         | 1         |
b         | 2         |
c         | 3         |

如何添加字母等级?

推荐答案

您的成绩字典可以如下创建:

Your grade dictionary can be created like:

grades = {1: 'C', 2: 'B', 3: 'A'}  # going by the sample output

{:> 7.2f} 将期望一个浮点数。只需使用 s 或离开类型格式化程序,不要指定精度。您的字典值是整数,所以我会使用 d 格式,而不是 f 。您的示例输出也显示为这些数字,而不是右对齐,因此格式说明符将需要'< 10d'

{:>7.2f} would expect a floating point number. Just use s or leave of the type formatter, and don't specify a precision. Your dictionary values are integers, so I'd use the d format for those, not f. Your sample output also appears to left align those numbers, not right-align, so '<10d' would be needed for the format specifier.

要包含成绩信,请查看 d [name] 作为关键字的成绩:

To include the grade letters, look up the grades with d[name] as the key:

format_str = '{:10s} | {:<10d} | {:>10s} |'
for name in sorted_d:
    print(format_str.format(name, d[name], grades[d[name]]))

演示:

>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> grades = {1: 'C', 2: 'B', 3: 'A'}  # going by the sample output
>>> sorted_d = sorted(d1)
>>> format_str = '{:10s} | {:<10d} | {:>10s} |'
>>> for name in sorted_d:
...     print(format_str.format(name, d1[name], grades[d1[name]]))
... 
a          | 1          |          C |
b          | 2          |          B |
c          | 3          |          A |

这篇关于从特定格式的字典打印值和键(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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