Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis0
Dictionaries
primes = {1: 2, 2: 3, 4: 7, 7:17} print(primes[primes[4]]) output:17 Please explain me how it works.
2 Respostas
+ 1
Hi! Compared to lists, the keys are the like the lists indices. In a dictionary, you find the key to the left, and the value to the right of the colon:
>> d0 = {key0: value0, key1: value1, ā¦, keyN: valueN}
# Assign a value to a key:
>> d0[keyP] = valueP
# Get the value for the key keyP:
>> d0[keyP]
valueP
# Example:
>> myList = [āaā, ābā]
>> myList[0]
a
>>
>> myDict = {1: ābā, 0: āaā}
>> myDict[0]
a
>>
The dictionaries have no special order between the element, like the elements in a list have. The key must also be immutable objects, like strings, numbers or tupples. You can mix and chose your keys as you line it, as long they are immutable and unique to each other; you can not have to identical keys. The values can be what ever you want, mutable or immutable objects, and donāt have to be unique comparing to orher values:
>> d2 = {(1, 2, 3): [3, 4], āhelloā: 67, āworldā: 67}
>> d2[(1, 2, 3)]
[3, 4]
>> d2[(1, 2, 3)][0]
1
>> d2[āhelloā]
67
In your example:
>> primes[4]
7
>> primes[7]
17
+ 2
primes[4] will return 7 and primes[7] will return 17 .
Inner expression is evaluated first which becomes output for outer expression