Python: word list comprehension for counting number of instances

I have the following:

a = rand(100).round() #for example
count = {}

for i in a:
    count[i] = count.get(i, 0) + 1

# print(a)
print(count)

      

The last line returns something like {0.0: 52, 1.0: 48}

I would like to make a for loop as a dictionary comprehension. But,

count = {i: count.get(i,0)+1 for i in a}

      

always returns {0.0: 1, 1.0: 1}

What am I doing wrong?

+3


source to share


3 answers


Statement

count = {i: count.get(i,0)+1 for i in a}

      

consists of two parts:

{i: count.get(i,0)+1 for i in a}

      

and



count = ...

      

the former evaluates the dictionary, and when evaluating it count

, it is just an empty dictionary that you defined first, and has nothing to do with the dictionary that is created by the expression of understanding.

Only at the end of the construction is the dictionary assigned count

(replacing the empty dictionary). During comprehension evaluation, it is count

empty and remains empty, so each get

will always return the default 0.

There is no way to refer to an object that is built in a comprehension (like a list or a dictionary) in expressions used within the comprehension.

+2


source


Why not use the assigned name Counter

?



from collections import Counter

>>> c = Counter([1,1,1,1,1,1,1,1,1,1,1,1,5,4,3,2,3,4,1,3,13,12,13,2,1,13,4,4,4])
>>> c
Counter({1: 14, 4: 5, 3: 3, 13: 3, 2: 2, 5: 1, 12: 1})

      

+3


source


I think your version of understanding looks like this:

count = {}
count = {i: count.get(i,0)+1 for i in a}

      

When comprehension is done, count

refers to the empty dictionary created on the previous line. Therefore, it count.get(i,0)

always returns 0

. This is why the result is 1

always. If you didn't specify on the previous line, you get

NameError: global name 'count' is undefined

Since count

it is not yet defined in the program.

Note. You cannot refer to a dictionary that is built in a dictionary comprehension.

So, updating the dictionary will not work in comprehension. The solution you actually have now is fine.

+1


source







All Articles