How to Access Dictionary Elements by Index in Python?

Mary-Kate Olsen
Release: 2024-11-08 01:24:03
Original
177 people have browsed it

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'}
}
Copy after login

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"]
Copy after login

This will return the following output:

{'American': '16', 'Mexican': 10, 'Chinese': 5}
Copy after login

To access a specific value within this sub-dictionary, use the following syntax:

mydict["Apple"]["American"]
Copy after login

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"]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!