Convert a nested for loop that increments the integer value of dictionary pair into a list comprehension

Convert a nested for loop that increments the integer value of dictionary pair into a list comprehension



Anyway to turn the for loop and its nested for loop into one list comprehension? I did not find this particular type of conversion anywhere.


from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
for token in text:
frequency[token] +=1




1 Answer
1



You can use collections.Counter:


collections.Counter


from collections import Counter
frequency = dict(Counter(token for text in texts for token in text))






elegant... didn't think to use Counter.

– spacedustpi
Sep 13 '18 at 3:36



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.