-1

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,
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
kcribb
  • 11
  • 1
  • 2
  • 3
    Possible duplicate of [python 3: print new output on same line](http://stackoverflow.com/questions/12032214/python-3-print-new-output-on-same-line) – smac89 Nov 09 '16 at 22:25

3 Answers3

2
for key, value in sorted(dict.items()):
    print ', '.join(("{} - {}".format(key, links)) for links in value)
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0
dictionary = {1: [2, 3], 2: [1, 4], 3: [2, 4], 4: [2, 3]}

for key, links in sorted(dictionary.items()):
    print("{key} - {}, {key} - {}".format(*links, key=key))
cdlane
  • 40,441
  • 5
  • 32
  • 81
0
>>> for key, value in sorted(d.items()):
        print('{} - {}, {} - {}'.format(key, value[0], key, value[1]))


1 - 2, 1 - 3
2 - 1, 2 - 4
3 - 2, 3 - 4
4 - 2, 4 - 3
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87