I have some list:
list = ["apple", "orange", "orange", "apple", "grape"]
I want to turn this into a dictionary where the key is the fruit, and the value is the number of times it occurs in the list. The list could be rather large, so it would be good for it to be linear time.
This is rather easy to do in a verbose way:
from collections import DefaultDict
dict_of_counts = DefaultDict(int)
for item in list:
dict_of_counts[item] += 1
This is clearly O(n) time, but it feels like I should be able to do it via a dictionary comprehension.
The only things I can think of though involve multiple calls to len
or count
, so it would be O(kn) time (where k is the distinct number of keys in my list).
Can someone point to a more "pythonic" way to do this (which I'd imagine involves the comprehension), or should I keep the above, verbose, implementation?