+ 10

Question about dictionaries

pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs) I'm a beginner. Could somebody explain to me why does this code print 1: False instead of 1: "apple" and doesn't print True: False.

29th Jul 2020, 10:26 AM
Sava
10 Respostas
+ 6
Sava True is the same as 1 and 0 is the same as False. Now, since you can't have keys of the same variable name (or value in this case) in a dictionary, the first key is chosen. Hope this helps 😃😃
29th Jul 2020, 10:40 AM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 3
Myself and Jan Markus already explained this. The most recent 1 will be outputted Eg. Let's add another True pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", True: 'programmer' } print(pairs) Output: 1: programmer,...
29th Jul 2020, 10:51 AM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
Thank you But I still don't understand why does the algorithm then print 1:false before orange
29th Jul 2020, 10:46 AM
Sava
+ 2
Thank you
29th Jul 2020, 10:51 AM
Sava
+ 2
I'm going to complicate things for you... my Python knowledge is a little out of date and I've just read that since 3.7, dictionary ordering can be guaranteed on insertion order. That means one of 2 things, either: 1) You are using an older version of Python Or 2) The behaviour is as such that the first key (1) remains in position 0 as it was inserted first and then the value is over-written when the subsequent pairs are added.
29th Jul 2020, 11:00 AM
benjamin
+ 2
When selecting a value from a dictionary or a list or an array for example, python uses zero-based indexing.this means that it starts counting at zero and not one as you may have expected.so the first value on the dictionary is on index 0
30th Jul 2020, 10:25 PM
Paul Ndambo Ngila
Paul Ndambo Ngila - avatar
+ 1
Dictionaries are not ordered so they will not necessarily output in the order they are written.
29th Jul 2020, 10:50 AM
benjamin
+ 1
In order to get the desired result you may use : print(pairs[1])
27th Feb 2022, 7:46 AM
Jaya Vishwakarma
Jaya Vishwakarma - avatar
0
The latest question was regarding order of output, not key uniqueness.
29th Jul 2020, 10:53 AM
benjamin
0
Yes I understood that but did not get why is it printed first instead of orange:[2,3,4] .
29th Jul 2020, 10:55 AM
Sava