Converting List of 3 Element Tuple to Dictionary

后端 未结 3 1494
情书的邮戳
情书的邮戳 2021-01-05 02:31

If I have two List of tuples

tuple2list=[(4, 21), (5, 10), (3, 8), (6, 7)]

tuple3list=[(4, 180, 21), (5, 90, 10), (3, 270, 8), (6, 0, 7)]

3条回答
  •  温柔的废话
    2021-01-05 03:29

    In Python2.7 or newer, you could use a dict comprehension:

    In [100]: tuplelist = [(4, 180, 21), (5, 90, 10), (3, 270, 8), (4, 0, 7)]
    
    In [101]: tuplelist2dict = {a:{b:c} for a,b,c in tuplelist}
    
    In [102]: tuplelist2dict
    Out[102]: {3: {270: 8}, 4: {0: 7}, 5: {90: 10}}
    

    In Python2.6 or older, the equivalent would be

    In [26]: tuplelist2dict = dict((a,{b:c}) for a,b,c in tuplelist)
    

    Note that if the first value in the tuples occurs more than once, (as in the example above) the resulting tuplelist2dict only contains one key-value pair -- corresponding to the last tuple with the shared key.

提交回复
热议问题