Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dictionary in python with a list as value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{(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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading