Consider a dictionary like the one below, created by parsing an input file within a Python function:
mydict = { 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} }
How can we access specific elements of this dictionary without knowing the key in advance?
To access elements of a dictionary, we use the dictionary's keys. To get the dictionary stored under the key "Apple", use the following syntax:
mydict["Apple"]
This will return the following output:
{'American': '16', 'Mexican': 10, 'Chinese': 5}
To access a specific value within this sub-dictionary, use the following syntax:
mydict["Apple"]["American"]
This will return the value '16', which represents the number of American apples.
Therefore, to access the first element of the "Apple" sub-dictionary, which is "American" in this case, you can use the following code:
first_element = mydict["Apple"]["American"]
The above is the detailed content of How to Access Dictionary Elements by Index in Python?. For more information, please follow other related articles on the PHP Chinese website!