Reputation: 55
Let's say I have a 2D list in Python:
mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
In this case my "keys" would be the first element of each array ("A" or "B") and my "values" would be the second element ("X" or "Y"). At the end of my consolidation the output should consolidate the keys and count the unique occurrences of values present for each key, i.e. something like:
# Output
# {"A":{"X":2, "Y":2}, "B":{"X":2, "Y":1}}
I am trying to use Python's itertools.groupby, but to no avail. Something similar to this question. If you have a better method, let me know.
Thanks!
Upvotes: 2
Views: 199
Reputation: 27273
I think the easiest way to do this would be with Counter and defaultdict:
from collections import defaultdict, Counter
output = defaultdict(Counter)
for a, b in mylist:
output[a][b] += 1
Upvotes: 12
Reputation:
L3viathan's answer seems to be better. However, this is another approach:
mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
dictionary = {"A": {"X": 0, "Y": 0}, "B": {"X": 0, "Y": 0}}
for x in mylist:
dictionary[x[0]][x[1]] += 1
Upvotes: 1