Skip to main content

Python: Access Dictionary

There are several ways to access Python Dictionary

1. By referring to key name:

The items of a dictionary can be accessed by referring to its key name, inside square brackets.

Example:

dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1[1])

Output: apple

There is also a method called get() that will give you the same result.

Example:

dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.get(1))

Output: apple

Note: If we use the square brackets []KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

2. By using key() method:

It will return a list of all the keys in the dictionary.

Example:

dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.keys())

Output: dict_keys([1, 2, 3])

3. By using value() method:

It will return a list of all the values in the dictionary.

Example:

dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.values())

Output: dict_values(['apple', 'papaya', 'pineapple'])

4. By using dict.items():

This method will return each item in a dictionary, as tuples in a list. It is also a good method to access dictionary keys with value.

Example:

dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
print(dict_1.items())

Output: dict_items([(1, 'apple'), (2, 'papaya'), (3, 'pineapple')])

5. By using in operator:

 This method is used to get possibly all the keys along with its value.

Example:

dict_1={1:'apple',2:'papaya',3:'pineapple'}
for i in dict_1 :
    print(i, dict_1[i])

Output:

1 apple
2 papaya
3 pineapple

6. By using enumerate():

It helps to iterate over all kinds of containers, be it dictionary or a list. It also additionally helps to access the named index of position of the pair in dictionary.

Example:

dict_1 = {1:'apple',2:'papaya',3:'pineapple'}
for i in enumerate(dict_1.items()):
    print (i)

Output:

(0, (1, 'apple'))
(1, (2, 'papaya'))
(2, (3, 'pineapple'))
Tags
Submitted by devanshi.srivastava on June 24, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.