I try 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?
What about:
This gives:
So you iterate over every
row
in thegroups
. The first element of the row is taken as value (row[0]
) and you iterate overrow[1:]
to obtain all the keysk
.Weird as it might seem, this expression also works when you give it an empty row (like
groups = [[],['A','B']]
). That is becauserow[1:]
will be empty and thus therow[0]
part is never evaluated:This is essentially a prettier version of Willem's:
But it won't work with an empty list:
groups = [[],['A','B']]
I think one line solution is a bit confusion. I would write code like below
I also like Willem's solution, but just for completeness...
another variation using itertools and a generator function (Python 3.x only)