简体   繁体   English

Python Print字典键,值是列表时的值。 在单独的行上打印每个键,值

[英]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. 我有一个Python字典,其中包含为该值定义的列表。 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,
for key, value in sorted(dict.items()):
    print ', '.join(("{} - {}".format(key, links)) for links in value)
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))
>>> 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
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM