Home > Mobile >  How to print multiple items to the same line while sepparating only some?
How to print multiple items to the same line while sepparating only some?

Time:02-15

I am trying to print dictionary keys with an arrow pointing to its value. The value must be a list and its items should be sepparated by a comma.

Suppose my dictionary is:

dicio["a"] = [1,2,3]
dicio["b"] = [4,5,6]
dicio["c"] = [7,8,9]

If I run:

>>>for key in dicio:
>>>    print(key, "->", *dicio[key], sep = ", ", file=output)

a, ->, 1, 2, 3
b, ->, 4, 5, 6
c, ->, 7, 8, 9

where every printed element has a comma following. I want the commas sepparating only the list elements, but it has to be everything in the same line, as follows:

a -> 1, 2, 3
b -> 4, 5, 6
c -> 7, 8, 9

How would I do that?

Thanks!

CodePudding user response:

dicio = {}
dicio["a"] = [1,2,3]
dicio["b"] = [4,5,6]
dicio["c"] = [7,8,9]

for k, v in dicio.items():
    print(f"{k} -> {', '.join([str(i) for i in v])}")

For every (key, value) contained in your dictionary .items() print they key, the arrow and the comma-separated string of the elements of the associated list value.

CodePudding user response:

dicio={}
dicio["a"] = [1,2,3]
dicio["b"] = [4,5,6]
dicio["c"] = [7,8,9]

for key in dicio:
    print(key, "->", (', '.join(str(i) for i in dicio[key])))

CodePudding user response:

Use Python String join() method

for k, v in dicio.items():
    print(f"{k} -> {','.join(map(str, v))}", file=output)
  • Related