I have a list of tuples like this:
[ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ]
I want to iterate through this keying by the first item, so, for example, I could print something like this:
a 1 2 3 b 1 2 c 1
How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...
Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
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.
l = [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] d = {} for x, y in l: d.setdefault(x, []).append(y) print d
produces:
{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
Slightly simpler...
from collections import defaultdict fq = defaultdict(list) for n, v in myList: fq[n].append(v) print(fq) # defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]})
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