kcribb kcribb - 29 days ago 13
Python Question

Python Print dictionary key, value when value is a list. Print each key, value on seperate line

I have a Python dictionary with a list defined for the value. I am having trouble printing the output in the format I need.

dict = {1 : [2,3], 2 : [1,4], 3 : [2,4], 4 : [2,3]}


Needed print format:

1 - 2, 1 - 3
2 - 1, 2 - 4
3 - 2, 3 - 4
4 - 2, 4 - 3


Code:

dict = {1 : [2,3], 2 : [1,4], 3 : [2,4], 4 : [2,3]}
for key, value in sorted(dict.items()):
for links in value:
print ("{} - {},".format(key, links)),


Output:

1 - 2, 1 - 3, 2 - 1, 2 - 4, 3 - 2, 3 - 4, 4 - 2, 4 - 3,


Or:

for key, value in sorted(dict.items()):
for links in value:
print ("{} - {},".format(key, links))

1 - 2,
1 - 3,
2 - 1,
2 - 4,
3 - 2,
3 - 4,
4 - 2,
4 - 3,

Answer
for key, value in sorted(dict.items()):
    print ', '.join(("{} - {}".format(key, links)) for links in value)