Python program for accessing elements from a dictionary

Here, we are going to learn how to access elements from a dictionary? Also, writing a Python program to access elements from a dictionary.
Submitted by Shivang Yadav, on March 21, 2021

There are some of the methods to access elements from a dictionary,

  1. By using key name
  2. By using get() method

1) Access elements by using key name

We can access the value of the dictionary by passing the key name inside the square brackets with the dictionary.

Syntax:

dictionary_name[key]

Program:

# Python program to access elements 
# from a Dictionary using key name

# Dictionary 
Record = {'id' : 101, 'name' : 'Amit Kumar', 'age' : 21} 

# accessing the elements
print("Dictionary \'Record\' elements...")
print(Record['id'])
print(Record['name'])
print(Record['age'])

Output:

Dictionary 'Record' elements...
101
Amit Kumar
21

2) Access elements by using get() method

The get() method can be used to access an item from the dictionary.

Syntax:

dictionary_name.get(key)

Program:

# Python program to access elements 
# from a Dictionary using get() method

# Dictionary 
Record = {'id' : 101, 'name' : 'Amit Kumar', 'age' : 21} 

# accessing the elements
print("Dictionary \'Record\' elements...")
print(Record.get('id'))
print(Record.get('name'))
print(Record.get('age'))

Output:

Dictionary 'Record' elements...
101
Amit Kumar
21

Python Dictionary Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.