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