Last active
June 20, 2018 09:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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