Python, how to print dictionary key and its values in each line?

前端 未结 4 1533
逝去的感伤
逝去的感伤 2021-01-29 14:23

Please see the below image for reference:

4条回答
  •  再見小時候
    2021-01-29 15:09

    You could do it with a single for loop unpacking a value list each iteration.

    d = {1: [2, 3], 2: [4, 5]}
    
    for k in d:
        x, y = d[k]
        print("{} : {}\n{} : {}".format(k, x, k, y))
    
    1 : 2
    1 : 3
    2 : 4
    2 : 5
    

    Because the value lists have just a couple numbers, it can also be done, like so:

    for k, v in d.items():
        print("{} : {}\n{} : {}".format(k, v[0], k, v[1]))
    

提交回复
热议问题