Nested list to dict
I think one line solution is a bit confusion. I would write code like below
groups = [['Group1', 'A', 'B'], ['Group2', 'C', 'D']]
result = {}
for group in groups:
for item in group[1:]:
result[item] = group[0]
print result
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'}