Q:

Python program for accessing elements from a dictionary

belongs to collection: Python Dictionary Programs

0

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

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program for accessing elements from a neste... >>
<< Python program to search student record stored usi...