0

Say you have a list of float values like this:

l=[0.1,0.3,0.2]

And a dictionary of lists like this: d1={0:[0.1,0.1,0.1,0.2], 1:[0.1,0.3,0.2], 2:[0.3,0.2,0.1]}

What would be a Pythonic way of counting how many times each value in l appears in the sublists of d1?

The intended outcome would be a dictionary of lists like this:

d2={0.1:[3,1,1], 0.2:[1,1,1], 0.3:[0,1,1]}

where the key is the value in l and the sublist contains the number of occurrences of each value.

Can this be done using Counter? The order of the values in the sublists is not important.

NB: this question is not the same as this other, where a list of dictionaries is involved.

Community
  • 1
  • 1
FaCoffee
  • 7,609
  • 28
  • 99
  • 174

1 Answers1

2

You can convert the lists inside d1 to Counter objects and gather them in a list. That list will then be used to get the number of occurrences of each element of l in every sublist while keeping the order:

In [12]: counters = [Counter(v) for v in d1.values()]

In [13]: {num: [c[num] for c in counters] for num in l}
Out[13]: {0.1: [3, 1, 1], 0.2: [1, 1, 1], 0.3: [0, 1, 1]}
vaultah
  • 44,105
  • 12
  • 114
  • 143