Skip to content Skip to sidebar Skip to footer

Printing Values And Keys From A Dictionary In A Specific Format (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 |

Solution 1:

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 |

Post a Comment for "Printing Values And Keys From A Dictionary In A Specific Format (python)"