Nested list to dict

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

    I also like Willem's solution, but just for completeness...

    another variation using itertools and a generator function (Python 3.x only)

    def pairs(groups):
        for value,*keys in groups:
            for key_value in zip(keys, itertools.repeat(value)): 
                yield key_value
    
    dict(pairs(groups))
    {'A': 'Group1', 'B': 'Group1', 'C': 'Group2', 'D': 'Group2'}
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题