0

I have the following:

thisdict = {"Romance": romance, "Horror": horror, 
            "Action": action, "Crime": crime, 
            "Si-fi": scifi, "Drama": drama, "Comedy": comedy}

print(thisdict)

for key, value in thisdict.items():
    print(key, ":", value)

and I want the output to have all the colons in alignment:

Horror : 5
Comedy : 4
Action : 2

How would I go about doing this?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
brian.p
  • 97
  • 6

2 Answers2

2

The best way is to make it like this:

thisdict = {"Romance": romance, "Horror": horror, "Action": action, "Crime": crime, "Si-fi": scifi, "Drama": drama, "Comedy": comedy}

print(thisdict)

spacer = len(max(thisdict, key=len))

for key, value in thisdict.items():
  print(f"{key:{spacer+1}}: {value}")

It's more readable and calculates spaces based on the longest string in the dictionary.

Freese
  • 177
  • 8
1
  1. Calculate the maximum length of the keys.
  2. Print key and space of (maximum key length - key length)
thisdict = {"Romance":1,"Horror":2,"Action":3,"Crime":4,"Si-fi":5,"Drama":6,"Comedy":7}

print(thisdict)

max_len = max(map(len, thisdict.keys()))
for key, value in thisdict.items():
    print(key + ' ' * (max_len-len(key)),":" , value)

The code ouputs the following.

{'Romance': 1, 'Horror': 2, 'Action': 3, 'Crime': 4, 'Si-fi': 5, 'Drama': 6, 'Comedy': 7}
Romance : 1
Horror  : 2
Action  : 3
Crime   : 4
Si-fi   : 5
Drama   : 6
Comedy  : 7
akamidori
  • 11
  • 2
  • You should also read about string-formatting (or just look at the link I provided above). Instead of multiplying a space, or calculating lengths, you can just do: `f'{key:{max_len}}'` – Tomerikoo Apr 26 '21 at 15:49
  • Use `.ljust(max_len)` instead of spacing things manually. – AKX Apr 26 '21 at 15:52