Given a nested list of tuples (this is the output of an itertools.groupby
operation on the 0th element:
l = [[(95, 'studentD')], [(97, 'studentB')], [(98, 'studentA'), (98, 'studentC')]]
Is there an easy way to obtain this?
{ 95 : 'studentD', 97 : 'studentB', 98: ['studentA', 'studentC']}
Note single elements are not placed within a list. Also, I can guarantee that all tuples in an inner list have the same x[0]
.
This is my solution:
In [203]: d = {}
In [204]: for x in l:
...: d.update({x[0][0] : ([y for _, y in x] if len(x) > 1 else x[0][1]) })
...:
In [205]: d
Out[205]: {95: 'studentD', 97: 'studentB', 98: ['studentA', 'studentC']}
Are there more elegant options that I am missing?