I have this nested list:
res=[(0, 0, 255, 0, 0),(1, 0, 255, 0, 0),(0, 1, 255, 0, 0),(1, 1, 255, 0, 0),
(4, 4, 0, 255, 0),(5, 4, 0, 255, 0),(4, 5, 0, 255, 0),(5, 5, 0, 255, 0)]
This is my idea:
keys = [l[2:] for l in res]
values = [l[:2] for l in res]
d=dict(zip(keys, values))
and this is my output:
{(255, 0, 0): (1, 1), (0, 255, 0): (5, 5)}
My output is wrong, I need this one:
{(255, 0, 0): [(0, 0),(1,0),(0,1),(1,1)],
(0, 255, 0): [(4,4),(5,4),(4,5),(5,5)]}
Any idea?
>Solution :
There are much more elegant solutions to this problem, but the point of the exercise is (likely) for you to practice logic and control flow, so I’ll show a more beginner-appropriate solution:
output = {}
for entry in res:
key, value = entry[2:], entry[:2]
if key not in output:
output[key] = []
output[key].append(value)
As has been mentioned though, collections.defaultdict(list) is the prime candidate for a problem like this.