+ 1

Python dictionaries

Hey everyone, So I'm learning Python dictionaries and there's a little exercise that blocks me, written below: primes = {1: 2, 2: 3, 4: 7, 7:17,} print(primes[4]) # 7 print(primes[primes[1]]) # 3 print(primes[primes[4]]) # 17 The first one got it, it prints the 4th number on the list but the other ones can't understand why? Tried different numbers and added even '9: 37' to see if the code checked if it's a prime number but the only message I get is Key Error. Hope my message is cleared, Bests,

17th Apr 2021, 5:45 PM
Da Silva Miguel
Da Silva Miguel - avatar
3 Respuestas
+ 2
your example works from sympy import isprime primes = {1: 2, 2: 3, 4: 7, 7:17, 9:37} print(primes[4]) # 7 print(primes[primes[1]]) # 3 print(primes[primes[4]]) # 17 for k, v in primes.items(): if isprime(v): print(k, v)
17th Apr 2021, 5:50 PM
minirkk
minirkk - avatar
+ 1
primes[1]=2 ----------1 primes[2]=3-----------3 primes[3]=4 Now , primes[primes[1]]-------2 from 1 , you substitute the value of primes[1] into 2 you get primes[2] which is 3
17th Apr 2021, 5:51 PM
Hima
Hima - avatar
+ 1
Ohhhhh right.... print(primes[primes[4]]) is the same saying: primes[4] = 7 therefore it gives print(primes[7]) # 17 Now I get it Thanks! @Rohit Thanks for that example, gonna keep it for later. I'm not there yet! ^^'
17th Apr 2021, 5:56 PM
Da Silva Miguel
Da Silva Miguel - avatar