Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

I have a list consisting of tuples with duplicates and I've converted them to a dictionary using this code I found here:

mylist = [(a,1),(a,2),(b,3)]    

result = {}

for i in mylist:  

   result.setdefault(i[0],[]).append(i[1])

print(result)

>>> result = {a:[1,2], b:[3]}

I recall learning that most for loops can be re-written as comprehensions so I wanted to practice but I've failed for the past hour to make one work.

1 Answer

0 votes
by (36.8k points)
edited by

Comprehension means to map the items in a sequence-independent of each other which is not suitable for aggregations. In your question, where the sub-list an item appends to depends on a sub-list with a previous item appends to.

You can produce the desired output with a nested comprehension if you must, but it would turn what would've been solved in O(n) time complexity with a loop into one that takes O(n ^ 2) instead:

{k: [v for s, v in mylist if s == k] for k, _ in mylist}

Improve your knowledge in data science from scratch using Data science online courses

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jun 11, 2020 in Data Science by blackindya (18.4k points)
0 votes
1 answer

Browse Categories

...