Nested list to dict

后端 未结 4 1739
忘掉有多难
忘掉有多难 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:47

    This is essentially a prettier version of Willem's:

    >>> groups = [['Group1', 'A', 'B'], ['Group2', 'C', 'D']]
    >>> {k:g for g,*tail in groups for k in tail}
    {'B': 'Group1', 'A': 'Group1', 'C': 'Group2', 'D': 'Group2'}
    

    But it won't work with an empty list:groups = [[],['A','B']]

    >>> {k:head for head, *tail in grps for k in tail}
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 1, in 
    ValueError: not enough values to unpack (expected at least 1, got 0)
    

提交回复
热议问题