Home > Software design >  I have made a dictionary using a list as the values for each key, I want to print the values without
I have made a dictionary using a list as the values for each key, I want to print the values without

Time:10-19

items = ['Item 1', 'Item 2', 'Item 3']
new_items = {'bacon': items, 'bread': items, 'cheese': items}
for key, value in new_items.items():
    print('{}: {}'.format(key, *value))

Output:

bacon: Item 1
bread: Item 1
cheese: Item 1

How do I get all of the items to print? If I remove the asterisk before value it prints all 3 items, but in square brackets.

CodePudding user response:

The question reduces to "how to convert a list to a string?". Some possible options which might suit you:

In [1]: items = ['Item 1', 'Item 2', 'Item 3']

In [2]: ' '.join(items)
Out[2]: 'Item 1 Item 2 Item 3'

In [3]: ', '.join(items)
Out[3]: 'Item 1, Item 2, Item 3'

CodePudding user response:

You can create the string to be output right in the format() method call:

items = ['Item 1', 'Item 2', 'Item 3']
new_items = {'bacon': items, 'bread': items, 'cheese': items}
for key, values in new_items.items():
    print('{}: {}'.format(key, ', '.join(values)))

Output:

bacon: Item 1, Item 2, Item 3
bread: Item 1, Item 2, Item 3
cheese: Item 1, Item 2, Item 3

CodePudding user response:

I think your problem is in how you construct new_items. Try this instead, then print:

items = ['Item 1', 'Item 2', 'Item 3']
labels = ['bacon', 'bread', 'cheese'}
new_items = zip(labels, items)

CodePudding user response:

Using f-strings:

items = ['Item 1', 'Item 2', 'Item 3']
new_items = {'bacon': items, 'bread': items, 'cheese': items}
for key, value in new_items.items():
    print(f'{key}: {", ".join(value)}')

Output:

bacon: Item 1, Item 2, Item 3
bread: Item 1, Item 2, Item 3
cheese: Item 1, Item 2, Item 3
  • Related