Trying To Add To Dictionary Values By Counting Occurrences In A List Of Lists (python)
I'm trying to get a count of items in a list of lists and add those counts to a dictionary in Python. I have successfully made the list (it's a list of all possible combos of occur
Solution 1:
Use a Counter
instead of an ordinary dict to count things:
from collections importCountershowcount= Counter()
for item in recs:
showcount.update(item)
or even:
from collections importCounterfrom itertools import chain
showcount = Counter(chain.from_iterable(recs))
As you can see that makes your code vastly simpler.
Solution 2:
If all you want to do is flatten your list of lists you can use itertools.chain()
>>>import itertools>>>listOfLists = ((1,3,4),(1,2,4),(1,4),(1,2),(1,4)) >>>flatList = itertools.chain.from_iterable(listOfLists)
The Counter object from the collections module will probably do the rest of what you want.
>>>from collections import Counter>>>Counter(flatList)
Counter({1: 5, 4: 4, 2: 2, 3: 1})
Solution 3:
I have some old code that resembles the issue, it might prove useful to people facing a similar problem.
import sys
file = open(sys.argv[-1], "r").read()
wordictionary={}
for word in file.split():
if word notin wordictionary:
wordictionary[word] = 1else:
wordictionary[word] += 1
sortable = [(wordictionary[key], key) for key in wordictionary]
sortable.sort()
sortable.reverse()
for member in sortable: print (member)
Solution 4:
First, 'flatten' the list using a generator expression: (item for sublist in combs for item in sublist)
.
Then, iterate over the flattened list. For each item, you either add an entry to the dict (if it doesn't already exist), or add one to the value.
d = {}
for key in (item for sublist in combs for item in sublist):
try:
d[key] += 1except KeyError: # I'm not certain that KeyError is the right one, you might get TypeError. You should check this
d[key] = 1
This technique assumes all the elements of the sublists are hashable and can be used as keys.
Post a Comment for "Trying To Add To Dictionary Values By Counting Occurrences In A List Of Lists (python)"