特定格式输出python_从特定格式的字典打印值和键(python)

I have this dictionary (name and grade):

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

and I have to print it like this:

|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'

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]))

It prints:

a | 1 |

b | 2 |

c | 3 |

How can I add the letter grade?

解决方案

Your grade dictionary can be created like:

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

{:>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.

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]]))

Demo:

>>> 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 |

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值