ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.