Accessing Values of Dictionary in Python


To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.

Example

Following is a simple example −

 Live Demo

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

Output

When the above code is executed, it produces the following result −

dict['Name']: Zara
dict['Age']: 7

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −

Example

 Live Demo

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

Output

When the above code is executed, it produces the following result −

dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updated on: 28-Jan-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements