0

I have the following dictionary baz, which is created by zipping the lists foo and bar:

foo = ['Blue', 'Red', 'Green']
bar = [1, 2, 3]

baz = dict(zip(foo, bar))

baz
{'Blue': 1, 'Red': 2, 'Green': 3}

I'd like to be able to print a comma-separated list of keys and values. To do so, I'm using:

for k, v in baz.items():
    print(f'{k} {v}, ', end='')

This works, but there is a trailing comma after the last dictionary value. What's the best way to remove that comma?

(I tried sep=',' but doing so removes the commas altogether)

Thanks!

equanimity
  • 2,371
  • 3
  • 29
  • 53
  • 1
    Use `','.join()` to create comma-separated lists, not a loop. – Barmar Feb 16 '22 at 22:37
  • @Barmar -- Thank you. Why doesn't `sep=','` give the desired output (as mentioned in https://stackoverflow.com/questions/32796452/printing-a-list-separated-with-commas-without-a-trailing-comma)? – equanimity Feb 17 '22 at 00:08
  • `sep` is only used when you give multiple arguments to a single `print()` call, it specifies how to separate them. If you just print one thing at a time in a loop, the separator isn't used. – Barmar Feb 17 '22 at 16:27

0 Answers0