Imagine we have a list of lists where the nested list contains two elements [A, B]. Now, you want to convert such list into a dictionary where the first element should be the key and the second element should be its value. For example:
[['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'B1'], ['B', 'C1'], ['C', 'B2'], ['C', 'C2'], ['C', 'D2']] -->
{'A': ['B', 'C', 'D'], 'B': ['B1', 'C1'], 'C': ['B2', 'C2', 'D2']}
The order of the values should be kept.
I have a straightforward solution:
lst = [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'B1'], ['C', 'C1']]
dic = {}
for el in lst:
if dic.get(el[0]) is None:
dic[el[0]] = [el[1]]
continue
dic[el[0]].append(el[1])
And an ugly list comprehension solution which is significantly slower because it performs a loop over complete data for each single key.
dic = dict([(el[0], [e[1] for r in lst if e[0] == el[0]])
for el in lst])
There should be a better and more elegant way to do this. Can you come up with something?