Search code examples
pythonfor-loopstring-formattingf-string

For loop padding print statements of dictionary by longest key


So I have this dictionary of names and values that I'm trying to print with spaces in between padded by the length of the longest key.

The code below does what I want, but the 17 is hard coded from my unit test and I'd like to replace it with the variable longest_key.

longest_key = max(len(x) for x in sorted_dict)
# longest_key is 17 for unit test
for k, v in sorted_dict:
    print("{0:<17}".format(k), v)

I tried doing what was written here: https://stackoverflow.com/a/54605046/2415706

like:

print("{0:<{longest_key}}".format(k), v)

And also using the global keyword but I keep getting a key error on longest_key. Thank you!

Update: For anyone reading this, this print mixes f-string (it's missing the f though . . . ) and .format. f-string is the newest thing and the most legible so go with that. It should just look like:

print(f"{k:<17} {v}")

Random bonus next part of my assignment, if you have to run functions on the values you can do that inside the {} like:

print(f"{some_function(k):<17} {some_other_function(v)}")

Solution

  • You seem to be mixing styles + another minor correction for looping key values in dict

    Adding multiple choices below to provide more clarity. In most of the choices, I take the liberty to assume you are using longest_key to pad as I do not see another reason for it to be computed in the code snippet

    sorted_dict = {"name": "Hello", "numbers1234567890": "seventeen"}
    
    longest_key = max(len(x) for x in sorted_dict)
    # longest_key is 17 for unit test
    
    for k, v in sorted_dict.items():
        print(f"{k:<17}", v)
    for k, v in sorted_dict.items():
        print(f"{k:<{longest_key}}", v)
    for k, v in sorted_dict.items():
        print(f"{k:<{longest_key}} {v}")
    
    # for python <3.6
    for k, v in sorted_dict.items():
        print("{0:<17}".format(k), v)
    for k, v in sorted_dict.items():
        print("{0:<{1}}".format(k, longest_key), v)
    for k, v in sorted_dict.items():
        print("{0:<{1}} {2}".format(k, longest_key, v))
    for k, v in sorted_dict.items():
        print("{0:<{width}} {1}".format(k, v, width=longest_key))
    

    I know there are other ways to do the same but I list just these as I expect them to add more clarity to the syntax of the code styles.