Reputation: 2924
I have a dict which contains string keys of different lengths. I want to obtain the following result when printing the dictionary:
'short-key' value1
'short-key2 value2
...
'little-longer-key' valueXX
...
'very-very-long-keeey' valueXXXX
Until now I've been doing something like this:
for key,value in dict.iteritems():
print key," "*(80-len(key)),value
PROBLEMS:
I don't like it. Doesn't really seem pythonic
80 is a usually-big-enough number randomly chosen. But sometimes it may happen the key is longer than that, therefore the " "*(80-len(key))
is useless
Upvotes: 0
Views: 510
Reputation: 8813
You will have to iterate twice to get the length of the longest key. List comprehensions can make that nicer. My personal preference is to only iterate on the keys of the dictionary and then do a lookup:
padded_width = max(len(x) for x in my_dict.iterkeys()) + 1
for key in my_dict:
print(key.ljust(padded_width) + my_dict[key])
Here's a fancier version that allows more control over the padding and uses string formatting:
SPACE_BETWEEN_KEYS_AND_VALUES = 1
MINIMUM_PADDING = 10
padded_width = max(MINIMUM_PADDING, max(len(x) for x in my_dict.iterkeys()) + SPACE_BETWEEN_KEYS_AND_VALUES)
for key in my_dict:
print("{key: <{width}}{value}".format(key=key, width=padded_width, value=my_dict[key]))
I think I prefer the string concatenation of the first example, personally.
Upvotes: 1