Recently, I was answering a question. The code worked as intended. But I wanted to see if I could implement dict comprehension which I rarely use. First of all, let me explain the problem.
The OP had an example list like M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
.
They wanted an output similar to this. [['a',14,7,16],['b',3,15],['c',22,1,5]]
. Makes sense, so I created an answer.
original code
x = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
dictX = {}
for lsts in x:
if lsts[0] in dictX.keys():dictX[lsts[0]].extend(lsts[1:])
else:dictX[lsts[0]] = lsts[1:]
output
{'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}
my go at this
x = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
dictX = {}
dictX ={(dictX[lsts[0]].extend(lsts[1:]) if lsts[0] in dictX.keys() else dictX[lsts[0]]): lsts[1:] for lsts in x}
Error
Traceback (most recent call last): File "/Users/aspera/Documents/Python/Py_Programs/data/timeComplexity/test.py", line 3, in dictX ={(dictX[lsts[0]].extend(lsts[1:]) if lsts[0] in dictX.keys() else dictX[lsts[0]]): lsts[1:] for lsts in x} File "/Users/aspera/Documents/Python/Py_Programs/data/timeComplexity/test.py", line 3, in dictX ={(dictX[lsts[0]].extend(lsts[1:]) if lsts[0] in dictX.keys() else dictX[lsts[0]]): lsts[1:] for lsts in x} KeyError: 'a'
My shot at this seems wrong in so many ways. I used this as a reference (top comment of accepted answer)
{(a if condition else b): value for key, value in dict.items()}
Is there any way I could turn this to dict comprehension. I'd like an example which goes along the lines of the reference I provided and the logic I have used in my original code