Converting List of 3 Element Tuple to Dictionary

后端 未结 3 1476
情书的邮戳
情书的邮戳 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:18

    If one wants a nested dictionary without overriding the dictionary, could use the defaultdict from the collections library.

    >>> from collections import defaultdict
    >>> # Edited the list a bit to show when overrides
    >>> tuple3list=[(4, 180, 21), (4, 90, 10), (3, 270, 8), (6, 0, 7)]
    >>> tuple3dict = defaultdict(dict)
    >>> for x, y, z in tuple3list:
    ...     tuple3dict[x][y] = z
    ... 
    >>> print(tuple3dict)
    defaultdict(, {4: {180: 21, 90: 10}, 3: {270: 8}, 6: {0: 7}})
    >>> tuple3dict[4][90]
    10
    

    Unfortunately, one line assignments are tricky or impossible, hence I assume the only valid solution would be this.

提交回复
热议问题