0

I've got a dictionary like this:

mapping = {
    'a':['_________','_________','_________'],
    'b':['---------','---------','---------'],
    'c':['=========','=========','========='],
}

And I need to print all the first items in the values lists printed on the first line, all the second values on the second line and all the third values on the third line. Like this:

_________---------=========
_________---------=========
_________---------=========

All items are the same amount of characters long and all lists have the same number of items.

I have a list of letters which gets the keys in the right order, I'm just not sure how to print the values. I can print all the first items with:

counter = 0
for l in letters:
      for value in mapping[l]:
        print(value[counter],end="")

How would I go about creating the output above?

GoatsWearHats
  • 272
  • 1
  • 9
  • 17

2 Answers2

1

You could 'transpose' your lists; the columns in the list have to become rows.

Once you have your lists in the right order, the zip() function can do the transposing for you:

right_order = (mapping[l] for l in letters)
transposed = zip(*right_order)
for column in transposed:
    print(*(column), sep='')

Demo:

>>> mapping = {
...     'a':['_________','_________','_________'],
...     'b':['---------','---------','---------'],
...     'c':['=========','=========','========='],
... }
>>> letters = 'abc'
>>> right_order = (mapping[l] for l in letters)
>>> transposed = zip(*right_order)
>>> for column in transposed:
...     print(*(column), sep='')
... 
_________---------=========
_________---------=========
_________---------=========

The alternative would be to use a row counter by using an outer loop over the number of elements in one of the lists:

for rownum in range(len(mapping['a'])):
    for l in letters:
        print(mapping[l][rownum], end='')
    print()
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You have to make sure you sort your dictionary, then iterate through it and print stuff.

length = len(d['a'])

for i in range(length):
    for key in sorted(d.keys()):
        print(d[key][i], end = '')
    print()
Ben
  • 5,952
  • 4
  • 33
  • 44