Nick Boukis
Nick Boukis

Reputation: 55

How to count multiple unique occurrences of unique occurrences in Python list?

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

Answers (2)

L3viathan
L3viathan

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

user4396006
user4396006

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

Related Questions