Eli
Eli

Reputation: 38949

How to Use a Dictionary Comprehension on a List of Non-Unique Items

Yesterday, I was working on a problem where I wanted to take a list of non-unique items and make a dictionary out of them that had unique versions of the items in the list mapped to the number of times each appeared. This sounds pretty straight forward, and I immediately started writing a dictionary comprehension for it, only to realize once I started that I had no idea how to finish because the keys I'm running through aren't unique, and the values should be additive. Still it feels like there ought to be an elegant dictionary comprehension for this. Ideas?

What I want is a comprehension that does the following:

#given
lst = [1,1,1,7,5,8,3,8,5,9,1]
#do
a_dict = defaultdict(int)
for item in lst:
    a_dict[item] +=1

Upvotes: 1

Views: 196

Answers (1)

Elias Zamaria
Elias Zamaria

Reputation: 101063

The Counter class in the collections module looks like it may do what you want.

You can do something like this:

from collections import Counter
a_dict = Counter(lst)

Versions of Python older than 2.7 do not have the Counter class, but you may be able to do something like this:

a_dict = dict((x, lst.count(x)) for x in set(lst))

The set conversion is not necessary. It may make the code run faster for large lists with many identical items but I don't know for sure because I haven't benchmarked it.

Upvotes: 3

Related Questions