Dict with same keys names

后端 未结 2 642
感动是毒
感动是毒 2021-01-16 03:16

I need a dictionary that has two keys with the same name, but different values. One way I tried to do this is by creating a class where I would put the each key name of my d

2条回答
  •  暖寄归人
    2021-01-16 04:12

    Instead of wanting multiple keys with the same name, could you getting away of having multiple values per each key?

    names = [1]
    values = [[1, 2, 3], [4, 5, 6]]
    
    dict = {}
    
    for i in names:
        dict[i] = values
    
    for k,v in dict.items():
        for v in dict[k]:
            print("key: {} :: v: {}".format(k, v))
    

    Output:

    key: 1 :: v: [1, 2, 3]
    key: 1 :: v: [4, 5, 6]
    

    Then you would access each value like this (or in a loop):

    print("Key 1 value 1: {}".format(dict[1][0]))
    print("Key 1 value 2: {}".format(dict[1][1]))
    

提交回复
热议问题