Nested list to dict

后端 未结 4 1740
忘掉有多难
忘掉有多难 2021-02-18 14:02

I am trying to create dict by nested list:

groups = [[\'Group1\', \'A\', \'B\'], [\'Group2\', \'C\', \'D\']]

L = [{y:x[0] for y in x i         


        
4条回答
  •  [愿得一人]
    2021-02-18 14:46

    What about:

    d = {k:row[0] for row in groups for k in row[1:]}
    

    This gives:

    >>> {k:row[0] for row in groups for k in row[1:]}
    {'D': 'Group2', 'B': 'Group1', 'C': 'Group2', 'A': 'Group1'}
    

    So you iterate over every row in the groups. The first element of the row is taken as value (row[0]) and you iterate over row[1:] to obtain all the keys k.

    Weird as it might seem, this expression also works when you give it an empty row (like groups = [[],['A','B']]). That is because row[1:] will be empty and thus the row[0] part is never evaluated:

    >>> groups = [[],['A','B']]
    >>> {k:row[0] for row in groups for k in row[1:]}
    {'B': 'A'}
    

提交回复
热议问题