Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter in Collections module Python

I've come across a really weird problem. I'm trying to use Counter function in collections module. However, I keep getting the same error message

AttributeError: 'module' object has no attribute 'Counter'

I have tried using it before and it worked fine, but now for some reason when I import "collections" module it has a very limited number of attributes.

I have tried:

import collections   # when calling Counter I would then use collections.Counter()
import collections as collect # collect.Counter()

For both of those I keep getting Attribute Error.

I have also tried

from collections import Counter

And in this case I got:

ImportError: cannot import name Counter

These are all tested both in ipython interface and through a script (not importing anything else, just the collections).

Any ideas?

like image 217
branwen85 Avatar asked Nov 09 '12 15:11

branwen85


People also ask

What is Counter in collections in Python?

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers. However there is no restriction on it's keys and values. Although values are intended to be numbers but we can store other objects too.

What does Counter from collections do?

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

What does Counter () do in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.

Is Counter a module in Python?

The Counter module, as the name suggests, can be used to count elements of an iterable or a hashable object in Python. Counter stores each element of an iterable (like a Python list object) as a Python dictionary key. Since Python dictionaries allow only unique keys, there is no repetition.


1 Answers

You should use a new version of python AS python 3. You can then use this module. Then import,

import collections
from collections import counter
like image 192
Asad Ashraf Karel Avatar answered Sep 22 '22 01:09

Asad Ashraf Karel