
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Accessing Values of Dictionary in Python
Accessing Values of Dictionary in Python
Accessing dictionary items in Python involves retrieving the values associated with specific keys within a dictionary data structure. Dictionaries are composed of key-value pairs, where each key is unique and maps to a corresponding value. Accessing dictionary items allows us to retrieve these values by providing the respective keys.
There are various ways to access dictionary items in Python. They include ?
- Using square brackets[]
- The get() method
- Using keys() Method
- Using values() Method
- Using for loop and items() method
Example
Following is a basic example to access all the elements of the dictionary ?
my_Dict = {1:'one',2:'two',3:'three',4:'four'} print("Dictionary :",my_Dict)
Output
Following is the output of the above code ?
Dictionary: {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Access Dictionary Items Using Square Brackets
In Python, the square brackets [] are used for creating lists, and accessing elements from a list or other iterable objects (like strings, tuples, or dictionaries).
We can access dictionary items using square brackets by providing the key inside the brackets. This retrieves the value associated with the specified key.
Example
In the following example, we have defined a dictionary containing states and capitals. We have accessed the capital city of Telangana using square brackets ?
my_Dict={'Telangana':'Hyderabad','Tamilnadu':'Chennai','Kerala':'Thiruvanthapuram','Karnataka':'Bangaluru'} print("Capital City of Telangana:",my_Dict['Telangana'])
Following is the output of the above code ?
Capital City of Telangana: Hyderabad
If the key value which is present inside the square brackets is not present it will raise a KeyError.
Example
In the following example, when we try to access the capital city of Odisha which is not defined in the dictionary it results in an Error ?
my_Dict={'Telangana':'Hyderabad','Tamilnadu':'Chennai','Kerala':'Thiruvanthapuram','Karnataka':'Bangaluru'} print("Capital City of Telangana:",my_Dict['Odisha'])
Following is the output of the above code ?
ERROR! Traceback (most recent call last): File "<main.py>", line 2, in <module> KeyError: 'Odisha'
Access Dictionary Items Using get() Method
The get() method in Python's dict class is used to retrieve the value associated with a specified key. If the key is not found in the dictionary, it returns a default value (usually None) instead of raising a KeyError.
We can access the items of the dictionary using the get() method by passing keys as an argument. We can customize any value instead of None when the key is not found in the dictionary.
Syntax
Following is the syntax to access key values of a dictionary using the get() method ?
dict.get(key, value)
Example
In the following example, we have accessed the values of the dictionary by passing keys as an argument to the get() method ?
my_Dict={'Telangana':'Hyderabad','Tamilnadu':'Chennai','Kerala':'Thiruvanthapuram','Karnataka':'Bangaluru'} Value=my_Dict.get('Tamilnadu') print("Capital City of Tamilnadu:",Value)
Following is the output of the above code ?
Capital City of Tamilnadu: Chennai
Example
The get() method doesn't raise a keyerror if the key is not found instead returns None ?
my_Dict={'Telangana':'Hyderabad','Tamilnadu':'Chennai','Kerala':'Thiruvanthapuram','Karnataka':'Bangaluru'} Value=my_Dict.get('Odisha') print("Capital City of Odisha:",Value)
Following is the output of the above code ?
Capital City of Odisha: None
Access Dictionary Items Using 'keys()' Method
The keys() method is used to return all the key values of the dictionary. These are immutable, meaning they cannot be changed once they are assigned. They must be of an immutable data type, such as strings, numbers, or tuples.
Syntax
Following is the syntax to access key values of a dictionary using the keys() method ?
dictionary.keys()
Example
In the following example, we have accessed all the key values of the dictionary using the key() method ?
my_Dict={'Telangana':'Hyderabad','Tamilnadu':'Chennai','Kerala':'Thiruvanthapuram','Karnataka':'Bangaluru'} print(my_Dict.keys())
Following is the output of the above code ?
dict_keys(['Telangana', 'Tamilnadu', 'Kerala', 'Karnataka'])
Access Dictionary Items Using 'values()' Method
In a dictionary, values() are the data associated with each unique key. They represent the actual information stored in the dictionary and can be of any data type, such as strings, integers, lists, other dictionaries, and more. Each key in a dictionary maps to a specific value, forming a key-value pair.
Syntax
Following is the syntax to access the values of the dictionary using the values() method ?
dictionary.values()
Example
Here, we have accessed the values of the dictionary using the values() method ?
my_Dict={1:'one',2:'two',3:'three',4:'four'} print(my_Dict.values())
Following is the output of the above code ?
dict_values(['one', 'two', 'three', 'four'])
Using 'for' loop and 'items()' method
The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple, or string. It performs the same action on each item of the sequence.
The Python dictionary items() method returns a view object of the dictionary. The view object consists of the key-value pairs of the dictionary, as a list of tuples.
Following is the syntax of the Python dictionary items() method ?
dict.items()
We can access all the keys and values of the dictionary by iterating through the for loop and items() method.
Example
In the following example, accessed keys and values of the dictionary using the for loop and items() method ?
my_Dict={1:'one',2:'two',3:'three',4:'four'} for key, value in my_Dict.items(): print((key,value),end=' ')
Following is the output of the above code ?
(1, 'one') (2, 'two') (3, 'three') (4, 'four')