I have a nested list [['A','B'],['A','C'],['D'],['C','A']]
import itertools
d = {}
for key, group in itertools.groupby([['A','B'],['A','C'],['D'],['C','A']], lambda x: x[0]):
d[key] = list(group)
print(d)
Now I will have {'A': [['A', 'B'], ['A', 'C']], 'D': [['D']], 'C': [['C', 'A']]}
However, since 'D' is the only nested list with a single element, I want all single-element to print out as a number 0
.
I want to output: {'A': [['A', 'B'], ['A', 'C']], 'D': 0, 'C': [['C', 'A']]}
, so I added an if-else clause and changed my code to:
for key, group in itertools.groupby([['A','B'],['A','C'],['D'],['C','A']], lambda x: x[0]):
if len(list(group)[0]) > 1:
d[key] = list(group)
else: d[key] = 0
print(d)
However, the above code printed out as {'A': [], 'D': 0, 'C': []}
. I didn't see anything wrong with my code. However, why do A
and C
print out an empty list?