Python code unable to understand the output

python

#1

a=dict()
a[1]

can anyone explain me the output of this code in python


#2

Hi @sachin70,

Your question is a bit unclear. What is dict() here? Is that a dictionary, is it a function you are calling?


#3

@sachin70: you are making a dictionary with name a.
Your dictionary is empty, so you can’t see any output.
assign some key value pair to it then check output.
a[1] = “sachin”
check out python dictionary for more.

Hope it is clear now.


#4

this is not clear question
first of all you assign a value in dictionary
a=dict(" rajesh")
than use a[1]


#5

you get Key error when try a[1] since there is no key called ‘1’

so if you want to add the elements to the dictionary you need to do like this:

a = dict()#Instantiating dict object
a[1] = 20
a[‘analytics’] = ‘vidhya’
now here you have two keys called 1,‘analytics’
now if you want to get the value of 20 you need access through key ex:a[1]
in case of list, tuple you can access the value using index.
ex:
a = [2,3,1]

where a[1] means value at index 1. so you get 3 as output.


#6

Read python dictionaries :slight_smile: