Converting List of 3 Element Tuple to Dictionary

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

    This pair-case is simple, since it aligns with dict construction:

    ... the positional argument must be an iterator object. Each item in the iterable must itself be an iterator with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.

    >>> t = [(4, 21), (5, 10), (3, 8), (4, 7)]
    >>> dict(t)
    {3: 8, 4: 7, 5: 10}
    

    The triple case could be solved in this way:

    >>> t = [(4, 180, 21), (5, 90, 10), (3, 270, 8), (4, 0, 7)]
    >>> dict([ (k, [v, w]) for k, v, w in t ])
    {3: [270, 8], 4: [0, 7], 5: [90, 10]}
    

    Or a bit more general:

    >>> dict([ (k[0], k[1:]) for k in t ]) # hello car, hi cdr
    {3: (270, 8), 4: (0, 7), 5: (90, 10)}
    

    Note that your code:

    _3_tuplelist_to_dict = {4: {180:21}, 5:{90:10}, 3:{270:8}, 4:{0:7}}
    

    is really just a confusing representation of this:

    {3: {270: 8}, 4: {0: 7}, 5: {90: 10}}
    

    Try:

    >>> {4: {180:21}, 5:{90:10}, 3:{270:8}, 4:{0:7}} == \
        {3: {270: 8}, 4: {0: 7}, 5: {90: 10}}
    True
    

    With Python 3, you can use a dict comprehension:

    >>> t = [(4, 180, 21), (5, 90, 10), (3, 270, 8), (4, 0, 7)]
    >>> {key: values for key, *values in t}
    {3: [270, 8], 4: [0, 7], 5: [90, 10]}
    

提交回复
热议问题