Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>>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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading