Home >Backend Development >Python Tutorial >How to Access Elements of a Python Dictionary by Index?
Accessing Elements of Python Dictionary by Index
In Python, dictionaries are collections of key-value pairs where each key is unique and associated with a specific value. To access elements of a dictionary, you need to use the corresponding key.
Consider the dictionary:
mydict = { 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} }
To access the first element of the 'Apple' key, which is 'American', follow these steps:
Retrieve the value associated with 'Apple':
apple_dict = mydict['Apple']
The apple_dict variable now contains the inner dictionary. To access 'American':
american_apples = apple_dict['American']
In your case, to print the first element of 'Apple', formatted as "American: 16", use the following code:
print("American:", mydict['Apple']['American'])
Note that the format of the input data may vary each time you run the application. However, the method described above will allow you to access elements by using the appropriate keys, regardless of the specific data.
The above is the detailed content of How to Access Elements of a Python Dictionary by Index?. For more information, please follow other related articles on the PHP Chinese website!