4

Given a dictionary of lists like this: d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]}

I want to be able to count how many times each individual value appears in all lists. In the example given, the intended outcome would be:

occurrences={0.1:4, 0.2:1, 1.1:1, 1.2:1, 2.1:1, 2.2:1}

I was thinking of using Counter in a line like this:

occurrences = Counter([k[0] for k in d.values()])

but the output is Counter({0.1: 1, 1.1: 1, 2.1: 1}), meaning that the previous line only counts the occurrences of the first element of each list.

How can I extend this count to all elements of all lists?

1
  • Are the elements in your lists floats? If so, you are going to need to define a tolerance in order to get meaningful results. Commented Oct 25, 2016 at 15:12

2 Answers 2

6

Since you don't appear to care about the keys of the dict, you can just use a comprehension:

>>> Counter(v for sublist in d.values() for v in sublist)
Counter({0.1: 4, 0.2: 1, 1.1: 1, 1.2: 1, 2.1: 1, 2.2: 1})
Sign up to request clarification or add additional context in comments.

Comments

3

You need to put all the value lists in one flat list and then count. You can pass the dictionary's list of values to itertools.chain.from_iterable to flatten them:

from collections import Counter
from itertools import chain

d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]}
c = Counter(chain.from_iterable(d.values()))
print(c)
# Counter({0.1: 4, 0.2: 1, 1.2: 1, 2.2: 1, 1.1: 1, 2.1: 1})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.