I have a list of tuples with duplicates and I've converted them to a dictionary using this code I found here:
https://stackoverflow.com/a/61201134/2415706
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.
I read this: https://stackoverflow.com/a/56011919/2415706 and now I haven't been able to find another library that does this but I'm also not sure if this comprehension I want to write is a bad idea since append mutates things.
This is the power of list comprehension. It can identify when it receives a string or a tuple and work on it like a list. You can do that using loops. However, not every loop can be rewritten as list comprehension.
A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.
Why you can not have duplicate keys in a dictionary? You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.
Comprehension is meant to map items in a sequence independent of each other, and is not suitable for aggregations such as the case in your question, where the sub-list an item appends to depends on a sub-list that 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With