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)}")