Skip to content
Advertisement

Is it possible to get binary count from Counter() Python

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:

data = [1,2,3,4,5,62,3,4,5,1]

I want the output to be:

Counter({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 62: 1})

Instead of:

Counter({1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 62: 1})

I am aware that I could loop through the Counter:

binary_count = {x: 1 for x in Counter(data)}

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:

>>> data = [1,2,3,4,5,62,3,4,5,1]
>>> dict.fromkeys(data, 1)
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 62: 1}
Advertisement