Home  >  Article  >  Backend Development  >  How to Access Dictionary Elements by Index in Python?

How to Access Dictionary Elements by Index in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 01:24:03177browse

How to Access Dictionary Elements by Index in Python?

Accessing Elements of a Python Dictionary by Index

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn