通过索引访问Python字典的元素 [英] Accessing elements of Python dictionary by index
问题描述
考虑像这样的字典
mydict = {
'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
'Grapes':{'Arabian':'25','Indian':'20'} }
例如,我如何访问该词典的特定元素? 例如,我想在格式化Apple的第一个元素(在我们的情况下仅是美国")之后打印第一个元素?
How do I access for instance a particular element of this dictionary? for instance, I would like to print the first element after some formatting the first element of Apple which in our case is 'American' only?
其他信息 上面的数据结构是通过在python函数中解析输入文件而创建的.创建后,该运行将保持不变.
Additional information The above data structure was created by parsing an input file in a python function. Once created however it remains the same for that run.
我正在函数中使用此数据结构.
I am using this data structure in my function.
因此,如果文件发生更改,则下次运行此应用程序时,文件的内容将有所不同,因此此数据结构的内容将有所不同,但格式将相同. 因此,您在我的职能中看到我,我不知道Apple中的第一个元素是'American'或其他任何元素,所以我不能直接使用'American'作为键.
So if the file changes, the next time this application is run the contents of the file are different and hence the contents of this data structure will be different but the format would be the same. So you see I in my function I don't know that the first element in Apple is 'American' or anything else so I can't directly use 'American' as a key.
推荐答案
鉴于这是您使用按键访问它的字典.获取存储在"Apple"下的词典,请执行以下操作:
Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:
>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}
要让他们中有多少是美国人(16),请执行以下操作:
And getting how many of them are American (16), do like this:
>>> mydict["Apple"]["American"]
'16'
这篇关于通过索引访问Python字典的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!