+ 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.
10 Answers
+ 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 đđ
+ 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,...
+ 2
Thank you
But I still don't understand why does the algorithm then print 1:false before orange
+ 2
Thank you
+ 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.
+ 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
+ 1
Dictionaries are not ordered so they will not necessarily output in the order they are written.
+ 1
In order to get the desired result you may use : print(pairs[1])
0
The latest question was regarding order of output, not key uniqueness.
0
Yes I understood that but did not get why is it printed first instead of orange:[2,3,4] .