Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

walrus operator in dict comprehension

I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator:

>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}

but this gave me the following error:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
  File "<pyshell#2>", line 1, in <dictcomp>
    q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
  NameError: name 'mean' is not defined

This error only happens when I try to use the variable, no problem while defining it:

>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if (sum(dic[x]) // len(dic[x])) > 65}
>>> mean
86
>>> q
{'B': 77, 'C': 87, 'D': 86}

Why? Where did I get it wrong?

like image 983
FAL Avatar asked Oct 05 '21 14:10

FAL


People also ask

What is the walrus operator?

The walrus operator creates an assignment expression. The operator allows us to assign a value to a variable inside a Python expression. It is a convenient operator which makes our code more compact. We can assign and print a variable in one go.

How does the walrus operator look in Python?

Assignment expression are written with a new notation (:=) . This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. The assignment expression allows you to assign True to walrus , and immediately print the value.

When was the walrus operator introduced Python?

The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.

How does the walrus operator look in Python group of answer choices name expression name expression name := expression name :: expression?

Walrus operator is the coolest feature that was added in the Python 3.8 update, the Python release that most of you are probably using right now. The operator := is called the walrus operator since it characterizes the look of the walrus. See the colon as eyes and the equal sign as its tusks.


1 Answers

Your code is roughly equivalent to

q = {}
for x in dic:
    if mean > 65:
        mean := ...
        q[x] = mean

which means you are using mean before assigning it.

You need to move the definition to the if-clause-section of the dict-comprehension.

>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: mean for x in dic if (mean := (sum(dic[x]) // len(dic[x]))) > 65}
>>> q
{'B': 77, 'C': 87, 'D': 86}

This translates to

q = {}
for x in dic:
    if (mean := ...) > 65:
        q[x] = mean
like image 189
timgeb Avatar answered Sep 18 '22 16:09

timgeb