A Python module that implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.
Questions tagged [python-collections]
129 questions
3
votes
2 answers
Collections.counter() is counting alphabets instead of words
I have to count no. of most occured word from a dataframe in row df['messages']. It have many columns so I formatted and stored all rows as single string (words joint by space) in one variabel all_words. all_words have all words seperated by space.…

Prometheous5
- 53
- 4
3
votes
2 answers
Combinations with Replacement and maximal Occurrence Constraint
from itertools import *
import collections
for i in combinations_with_replacement(['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'],15):
b = (''.join(i))
freq = collections.Counter(b)
for k in freq:
if freq [k] <…

tseries
- 723
- 1
- 6
- 14
3
votes
2 answers
How to make subset of Counter?
I am experimenting with Python standard library Collections.
I have a Counter of things as
>>> c = Counter('achdnsdsdsdsdklaffaefhaew')
>>> c
Counter({'a': 4,
'c': 1,
'h': 2,
'd': 5,
'n': 1,
's': 4,
…

Jay Patel
- 137
- 7
3
votes
3 answers
Python Counter to list of elements
Now to flatten Counter element i'm using the code
import operator
from collections import Counter
from functools import reduce
p = Counter({'a': 2, 'p': 1})
n_p = [[e] * p[e] for e in p]
f_p = reduce(operator.add, n_p)
# result: ['a', 'a',…

Ali SAID OMAR
- 6,404
- 8
- 39
- 56
3
votes
2 answers
Python Counter() function to count words in documents with more then one occurrence
I am working on an NLP (Natural Language Processing) project where I used the Python Counter() function from collections library. I am getting the results in the following form:
OUTPUT:
Counter({'due': 23, 'support': 20, 'ATM': 16, 'come': 12,…

Muhammad Sulaman Toor
- 43
- 1
- 1
- 6
3
votes
1 answer
Best way to do a fuzzy key lookup in Python?
I have a problem where I need to do a fuzzy lookup in a hash map, i.e. return the value corresponding to that key that most closely resembles the query, in my case measured by the Levenshtein distance.
My current approach is to subclass dict with a…

gmolau
- 2,815
- 1
- 22
- 45
3
votes
1 answer
What is the time complexity of iterating through a deque in Python?
What is the time complexity of iterating, or more precisely each iteration through a deque from the collections library in Python?
An example is this:
elements = deque([1,2,3,4])
for element in elements:
print(element)
Is each iteration a…

perseverance
- 6,372
- 12
- 49
- 68
3
votes
1 answer
How to ignore case while doing most_common in Python's collections.Counter?
I'm trying to count the number of occurrences of an element in an iterable using most_common in the collections module.
>>> names = ['Ash', 'ash', 'Aish', 'aish', 'Juicy', 'juicy']
>>> Counter(names).most_common(3)
[('Juicy', 1), ('juicy', 1),…

kmario23
- 57,311
- 13
- 161
- 150
2
votes
1 answer
Fast way to create a nested dictionary from a list of tuples without a for loop
I know similar questions have been asked before but I cannot find an adequate answer to my situation.
Let's say I have the following list of tuples:
d = [('first', 1), ('second', 2), ('third', 3)]
I can convert this very easily into a…

besi
- 171
- 1
- 9
2
votes
2 answers
How to sort the frequency of each letter in a descending order Python?
import collections
MY_FUN_STR = filter(str.isalpha, (str.lower("ThE_SLATe-Maker")))
frequencies = collections.Counter(MY_FUN_STR)
a = sorted(frequencies, reverse=True)
for letter in frequencies:
print ('{} appears {}'.format(letter,…

Doug
- 21
- 1
2
votes
2 answers
Python defaultdict(default) vs dict.get(key, default)
Suppose I want to create a dict (or dict-like object) that returns a default value if I attempt to access a key that's not in the dict.
I can do this either by using a defaultdict:
from collections import defaultdict
foo = defaultdict(lambda:…

jidicula
- 3,454
- 1
- 17
- 38
2
votes
1 answer
Summing up collections.Counter objects using `groupby` in pandas
I am trying to group the words_count column by both essay_Set and domain1_score and adding the counters in words_count to add the counters results as mentioned here:
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d …

Hazem Alabiad
- 1,032
- 1
- 11
- 24
2
votes
2 answers
How a class having only the '__getitem__' method defined support the 'in' operator?
If I have the following defined:
Card = namedtuple('Card', ['rank', 'suit'])
class CardDeck():
ranks = [str(x) for x in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards =…

adnanmuttaleb
- 3,388
- 1
- 29
- 46
2
votes
1 answer
how to print the element at front of a queue python 3?
import queue
q = queue.Queue()
q.put(5)
q.put(7)
print(q.get()) removes the element at front of the queue. How do i print this element without removing it? Is it possible to do so?

Ankit Jain
- 33
- 1
- 1
- 8
2
votes
3 answers
What is the most efficient way to sum a dict with multiple keys by one key?
I have the following dict structure.
product1 = {'product_tmpl_id': product_id,
'qty':product_uom_qty,
'price':price_unit,
'subtotal':price_subtotal,
'total':price_total,
}
And then a list of products, each item in the list is a dict with the above…

Mariano DAngelo
- 920
- 5
- 18
- 39