Dictionaries (Python) | SoloLearn: Learn to code for FREE!


Dictionaries (Python)

squares = {1: 1, 2: 4, 3: "error", 4: 16,} squares[8] = 64 squares[3] = 9 print(squares) Can someone explain me this? Here squares[8] is the index value or how do we check that basically. As in is it calculated the same way has lists?

4/14/2020 6:47:34 PM


3 Answers

New Answer


For dictionaries when you write like squares[8] = 64 then if the key 8 exists, then it's value is updated and if the key does not exists then a new key-value pair (8-64) is created and inserted into the dictionary. After seeing the output, it should have been clear what is happening.


There are no indexes in a dictionary, just keys. So squares[ key ] == value ( If you put something in the [] that is not in dictionary like squares [ "anything" ] It will give a "key" error not "index" out of bound )


squares is a dictionary. Where the value to the left of the colon : is the key to access the items value to the right of the colon. squares[8] = 64 and squares[3] = 9 Will change the value to the right of the colon if the item with the given key exists, or it will append the item to the dictionary if it does not. The value in the brackets [ ] is the key and the value to the right of = is that items value.