Using Counter()
, I want to do a binary count of variables in a list. So instead of getting the count for each variable, I would simply like to have a Counter()
variable, in which all values are one.
So for a given list:
JavaScript
x
2
1
data = [1,2,3,4,5,62,3,4,5,1]
2
I want the output to be:
JavaScript
1
2
1
Counter({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 62: 1})
2
Instead of:
JavaScript
1
2
1
Counter({1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 62: 1})
2
I am aware that I could loop through the Counter:
JavaScript
1
2
1
binary_count = {x: 1 for x in Counter(data)}
2
However, that does require looping through the dictionary once and seems unnecessary to me.
Advertisement
Answer
This isn’t what a Counter
is for, so whatever you do will require modifying the output.
Why not just not use a Counter
to begin with? This should be trivial with a regular dict
.
Heck, you can even just use dict.fromkeys
, so:
JavaScript
1
4
1
>>> data = [1,2,3,4,5,62,3,4,5,1]
2
>>> dict.fromkeys(data, 1)
3
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 62: 1}
4