Question about dictionaries | Sololearn: Learn to code for FREE!

+5

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.

7/29/2020 10:26:49 AM

Sava

10 Answers

New Answer

+8

The key 'True' will be converted internally to '1'. Then there you have two key-value-pairs with a key of '1'. If you print the whole dictionary then you will only see the latest key-value-pair with the key '1' and that is in your case the one which is assigned to the value 'False'.

+4

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 😃😃

+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

Thank you But I still don't understand why does the algorithm then print 1:false before orange

+1

Thank you

+1

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,...

+1

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.

0

Dictionaries are not ordered so they will not necessarily output in the order they are written.

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] .