A list as a key for a dictionary

前端 未结 5 1908
一整个雨季
一整个雨季 2021-01-22 08:28

I have multiple lists of tuples eg

[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]

that I would like to have as keys to a dictionary (so each key in my dic

5条回答
  •  梦毁少年i
    2021-01-22 08:48

    Use repr

    class A:
        pass
    
    import time
    
    # A and time as heterogenous elements, only to show the generality of my solution
    
    li_li = [ [([1,2,3,4],2),([5,6,7],3)] ,
              [([10,20,3],2),      ([5,6,77],3)] ,
              [([1,2,3,4],2),([5,6,time,7],3),([875,12], ['jk',78], A, (100,23),'zuum')] ]
    
    
    
    
    didi = {}
    for i,li in enumerate(li_li):
        didi[repr(li)] = i
    
    print 'dictionary  didi:'
    for k,v in didi.iteritems():
        print k,'     ',v
    
    print '----------------------------------'
    
    print didi[repr([([1+1+1+1+1+5,         200000/10000,    3],2),([5,8-2,7*11],3)      ])]
    

    result

    dictionary  didi:
    [([1, 2, 3, 4], 2), ([5, 6, , 7], 3), ([875, 12], ['jk', 78], , (100, 23), 'zuum')]       2
    [([1, 2, 3, 4], 2), ([5, 6, 7], 3)]       0
    [([10, 20, 3], 2), ([5, 6, 77], 3)]       1
    ----------------------------------
    1
    

提交回复
热议问题