0

an exercise requires me to write a list comprehension (where the keys should be divisible by 2 and in a range 0-10; the value for each key should be equal to the square of the key) that returns the following output.

my_dict = { (write code here) for num in (write code here) if (write code here)}

I have tried the following code but I am obviously making some mistakes.

my_dict = {num**2 for num in range(0,10) if float(num/2)==False}
my_dict

Could any of you help me understand how it should be done?

thank you very much

Cz_
  • 371
  • 2
  • 8
Michele Giglioni
  • 329
  • 4
  • 15
  • Hi please edit the results generated by your code into your question as text (i.e. not as an image). – DisappointedByUnaccountableMod Jul 14 '20 at 12:43
  • `if float(num/2)==False` Unless `num` is `0`, `num/2` will never be `0`, hence `float(num/2)==False` will never be `True` – DeepSpace Jul 14 '20 at 12:43
  • `float(num/2)==False` is **not** how you check for parity. See https://stackoverflow.com/questions/13636640/python-checking-odd-even-numbers-and-changing-outputs-on-number-size – DeepSpace Jul 14 '20 at 12:44
  • [PEP-274](https://www.python.org/dev/peps/pep-0274/#:~:text=This%20PEP%20proposes%20a%20similar,objects%20instead%20of%20list%20objects) – Sayandip Dutta Jul 14 '20 at 12:44
  • Note that you want to use `num: num**2` in the first spot. What you have currently is a `set` comprehension not a `dict` comprehension. – 0x5453 Jul 14 '20 at 12:45
  • Errr... Why is this question labelled as duplicate ? – Naeio Jul 14 '20 at 12:47

1 Answers1

0

Try

my_dict = {num : num ** 2 for num in range(10) if num % 2 == 0}
print(my_dict)

Output

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17