Rearrange dictionary to diplay tabular format

Hello all i have a quick question…I have result dictionary as shown below. Would like to rearrange to display desired output.

input
{53: 63, 54: 63, 55: 63}


output
53: 63
54: 63
55: 63

thanks

I’ll point you towards some notes I’ve written up on this previously: Dictionaries - Beginning Python Specifically, the use of the .items() method when looping over a dictionary will give you both the key and the value for each item. You can then chose to print them out however you wish, e.g. like print(f"{key}: {value}").

See what you can get using the .items() method in the loop and if you need more help, show us the code you’ve get and the output it gives and we can give another pointer.

1 Like

Thanks a lot @milliams …possible to store this into variable? thanks
Because i want to attach this info to email…thanks

Yes, instead of printing in the loop, you can save it out into a variable.

For example, if your loop was:

input = {53: 63, 54: 63, 55: 63}

for k, v in input.items():
    print(f"{k}: {v}")

you could change it to be:

input = {53: 63, 54: 63, 55: 63}

outputs = []  # make an initially empty list
for k, v in input.items():
    outputs.append(f"{k}: {v}")  # add each item into the list `outputs`

output = "\n".join(outputs)  # join the list of strings with newlines

# `output` now contains what you want, so you can print it or email it or whatever
print(output)

Finally, if you want to get clever, you could do this more succinctly with:

input = {53: 63, 54: 63, 55: 63}

output = "\n".join(f"{k}: {v}" for k, v in input.items())

print(output)
1 Like

Oh i love u @milliams you so generous for sharing this…have a great day!