Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dictionary Comprehension

Enes artun
PLUS
Enes artun
Courses Plus Student 2,364 Points

if statement placement and products_usd.value error.

Hi. I tried to add the if statement before for statement like in the previous video but got invalid syntax error. Why?

products_aud = {product:price*usd_to_aud if products_usd.values() < 5 for(product, price) in {'butter': 5.5, 'garlic': 3.5, 'parsley': 1.2}.items()}
Enes artun
Enes artun
Courses Plus Student 2,364 Points

Other problem is with the if products_usd.value() statement. I get '<' is not supported between instances of 'dict_values' and 'int'. They are integers aren't they or dict takes everything as string?

1 Answer

Steven Parker
Steven Parker
231,198 Points

It looks like you placed a simple conditional between the expression and the for loop in the comprehension.

But the previous video showed an if condition with an "else" clause to make sure some value was generated for each iteration.

If you want no value at all to be generated based on the condition, then the condition should go at the end of the comprehension, as is done in the examples shown in this video.

Enes artun
Enes artun
Courses Plus Student 2,364 Points

I see. It needs an else statement to function then. What about the python if products_usd.values() < 5 line? Why I am getting "" '<' is not supported between instances of 'dict_values' and 'int'. "" error?

Steven Parker
Steven Parker
231,198 Points

The code above doesn't show how "products_usd" is defined, but if it is the same as in the video, it's a dictionary with 3 entries. In that case the ".values()" method would return a sequence containing the 3 values, and comparing an entire sequence to a single int value ("5") with an inequality operator ("<") is not supported.

If you're trying to filter the items based on on the value after exchange rate conversion, the technique for that is shown in the latter part of the video.