printing values and keys from a dictionary in a specific format (python)

2024/10/6 22:26:14

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?

Answer

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 |
https://en.xdnf.cn/q/118899.html

Related Q&A

stdscr.getstr() ignore keys, just string

I just need convert entered text(bytes) to string. But if i on cyrillic press Backspace and some character, python throw me this error:UnicodeDecodeError: utf-8 codec cant decode byte 0xd0 in position …

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers?

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers? How should the initialization be done?line = [0] * 4 matrix = [line, line, line, line]

Creating a Data Pipeline to BigQuery Using Cloud Functions and Cloud Scheduler

I am trying to build a Data Pipeline that will download the data from this website and push it to a BigQuery Table. def OH_Data_Pipeline(trigger=Yes):if trigger==Yes:import pandas as pdimport pandas_gb…

Matching several string matches from lists and making a new row for each match

I have a data frame with text in one of the columns and I am using regex formatted strings to see if I can find any matches from three lists. However, when there are multiple matches from list 1, I wan…

Join and format array of objects in Python

I want to join and format values and array of objects to a string in python. Is there any way for me to do that?url = "https://google.com", search = "thai food", search_res = [{&q…

Copying text from file to specified Excel column [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…

Name error: Variable not defined

Program calculates the shortest route from point, to line, then to second point. Also I need to say how long is from the start of the line, to where point crosses. My code so far: from math import sqrt…

Error while deploying flask app on apache

I have a file manage.py, import os from app import create_app app = create_app(os.getenv(FLASK_CONFIG) or default) if __name__ == __main__:app.run()manage.py is working fine when tested in debug mode. …

Selenium Python get_element by ID failing

Can someone help me understand why my code fails to find the element by ID. Code below:from selenium import webdriver driver=webdriver.Firefox() driver.get(https://app.waitwhile.com/checkin/lltest3/use…

Pipelining POST requests with python-requests

Assuming that I can verify that a bunch of POST requests are in fact logically independent, how can I set up HTTP pipelining using python-requests and force it to allow POST requests in the pipeline?D…