0

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.

0

1 Answer 1

4

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I wasn't aware of this dict option
@Emil If the values aren't important, you could even consider using a set, which is similar to a dict without values.

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.