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?
source to share
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.
source to share
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.
source to share