a79ce734e1
a79ce734e1

Reputation: 875

Printing dictionary pair and next iteration's pair on one line in columns

I have a long list of 100+ unique (names don't repeat) key/value pairs which I'd like to print consolidated into two equal width columns.

Current loop:

for key in example:
    print(f'{key}: {example[key]}')

Example dictionary:

example = {
    'key0': 'val0',
    'key1': 'val1',
    'key2': 'val2',
    'key3': 'val3',
    'key4': 'val4',
    'key5': 'val5'
}

Desired result:

key0: val0            key1: val1
key2: val2            key3: val3
key4: val4            key5: val5

Upvotes: 2

Views: 132

Answers (5)

thebjorn
thebjorn

Reputation: 27311

If you want to print formatted data to the console, maybe use the rich library?

from rich.console import Console
from rich.table import Table
from itertools import zip_longest

console = Console()
table = Table(show_header=False)

lst = iter(example.items())

for (k1, v1), (k2, v2) in zip_longest(lst, lst, fillvalue=("", "")):
    table.add_row(k1, v1, k2, v2)

console.print(table)

output (looks even better on an actual console...):

┏━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┓
┃ key0 ┃ val0 ┃ key1 ┃ val1 ┃
│ key2 │ val2 │ key3 │ val3 │
│ key4 │ val4 │ key5 │ val5 │
│ key6 │ val6 │      │      │
└──────┴──────┴──────┴──────┘

Upvotes: 0

Nicolas Perez
Nicolas Perez

Reputation: 354

This works:

example = {
    "key0": "val0",
    "key1": "val1",
    "key2": "val2",
    "key3": "val3",
    "key4": "val4",
    "key5": "val5",
}

max_width = max([len(f"{k}: {v}") for k, v in example.items()])
column_width = max(40, max_width)

keys = list(example.keys())
values = list(example.values())

for i in range(0, len(keys) - 1, 2):
    left_key = keys[i]
    right_key = keys[i + 1]
    left_value = values[i]
    right_value = values[i + 1]
    n_spaces = column_width - len(f"{left_key}: {left_value}")

    print(f"{left_key}: {left_value}" + " " * n_spaces + f"{right_key}: {right_value}")

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

Another method:

from itertools import zip_longest

i = iter(example.items())

for col1, col2 in zip_longest(i, i):
    col1 = f"{col1[0]}: {col1[1]}"
    col2 = f"{col2[0]}: {col2[1]}" if col2 else ""
    print(f"{col1:<40} {col2:<40}")

Prints:

key0: val0                               key1: val1                              
key2: val2                               key3: val3                              
key4: val4                               key5: val5                              

Upvotes: 0

Ohad Sharet
Ohad Sharet

Reputation: 1142

you can run over the list of keys two by two

keys = list(example.keys())
for i in range(0,len(keys),2):
    key1 = keys[i]
    key2 = keys[i+1]
    print("%s:%s       %s:%s"%(key1,example[key1],key2,example[key2]))

output:

key0:val0       key1:val1
key2:val2       key3:val3
key4:val4       key5:val5

Upvotes: 2

Barmar
Barmar

Reputation: 780974

Please don't ask two different questions. I'll just answer how to loop over the dictionary the way you want. There are plenty of other questions that explain how to format into fixed-width fields.

Use itertools.islice() to slice the odd and even elements of the dictionary, then use zip() to pair them up.

from itertools import islice, zip_longest

for (key1, value1), (key2, value2) in \
        zip_longest(islice(example.items(), 0, None, 2), 
                    islice(example.items(), 1, None, 2), 
                    fillvalue = (None, None)):
    if key2 is not None:
        print(f'{key1}: {value1}  {key2: value2}')
    else:
        print(f'{key1}: {value1}')

Upvotes: 1

Related Questions