0
Dictionaries
primes = {1: 2, 2: 3, 4: 7, 7:17} print(primes[primes[4]]) output:17 Please explain me how it works.
2 Respuestas
+ 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