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

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

Please see the below image for reference:

相关标签:
4条回答
  • 2021-01-29 14:57

    Probably something like this:

    d = {1:[2,3], 2:[4,5]}
    
    for key in d:
        for i in d[key]:
            print("{0}:{1}".format(key, i))
    
    
    1:2
    1:3
    2:4
    2:5
    
    0 讨论(0)
  • 2021-01-29 14:59
    >>> for key in d:
    ...     for item in d[key]:
    ...         print key, ':', item
    1 : 2
    1 : 3
    2 : 4
    2 : 5
    
    0 讨论(0)
  • 2021-01-29 14:59

    use key and value of your dictionary

    d={1:[2,3],2:[4,5]}
    for k, v in d.items():
        for item in v:
            print(k,' : ',item)
    
    0 讨论(0)
  • 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]))
    
    0 讨论(0)
提交回复
热议问题