Skip to content

Instantly share code, notes, and snippets.

@jflanaga
Last active June 20, 2018 09:26
Show Gist options
  • Save jflanaga/b542a5ebddce318890eb772436cdcfc3 to your computer and use it in GitHub Desktop.
Save jflanaga/b542a5ebddce318890eb772436cdcfc3 to your computer and use it in GitHub Desktop.
Count values for each key in a dictionary when values are in a list or sublist
# Count values in a dictionary when values are in a list
d2 = {'a': ['I','said','that', 'I'],'b': ['she','was','here']}
from collections import Counter
counts = {k: Counter(v) for k, v in d2.items()}
# Count items in sublists
lst = [['I', 'said', 'that'], ['said', 'I']]
Counter(word for sublist in lst for word in sublist)
# Combining the two
from collections import Counter
d = {'a': [['I', 'said', 'that'], ['said', 'I']],
'b': [['she', 'is'], ['he', 'was']]}
counts = {k: Counter(word
for sublist in lst
for word in sublist)
for k, lst in d.items()}
print(counts)
# output
# {'a': Counter({'I': 2, 'said': 2, 'that': 1}),
# 'b': Counter({'she': 1, 'is': 1, 'he': 1, 'was': 1})}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment