Search code examples
pythonlistdictionarylist-comprehension

Nested list to dict


I am trying to create dict by nested list:

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

L = [{y:x[0] for y in x if y != x[0]} for x in groups]
d = { k: v for d in L for k, v in d.items()}

print (d)
{'B': 'Group1', 'C': 'Group2', 'D': 'Group2', 'A': 'Group1'}

But it seems a bit complicated.

Is there a better solution?


Solution

  • 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'}