从python字典访问特定元素 [英] accessing specific elements from python dictionary

查看:115
本文介绍了从python字典访问特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道是否有人提到稍早一些的问题,但
访问python字典的元素

Not sure if people refer to slightly older questions but Accessing elements of python dictionary

考虑像

dict = {
        'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
        'Grapes':{'Arabian':'25','Indian':'20'} 
       }

如何访问这个例子的一个特定元素字典?例如,我想在第一个元素格式化Apple的第一个元素之后打印第一个元素,在我们的例子中,我们的例子是'American'

How do I access for instance a particular element of this dictionary ? for instance I would like to print 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 file are different and hence the contents of this data structure will be different but the format would be 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.

总之,作为一个输入我有一个变量 v 可能有价值'apple''grape'或任何其他和上述创建的数据结构作为我的函数的输入。

In short as an input I have a variable v which may have value 'apple' , 'grape' or any other and the above created data structure as an input to my function.

如果变量存在于上述数据结构指令中,

If variable is present in above Data Structure Dict,

因此,如果 variable = = apple 葡萄然后:
然后我需要获得相应的相关元素,并以这样的特定格式打印它们; / p>

Thus if variable==apple or grapes then : then I need to get it's corresponding associated elements and print them in a specific format like this ;

Group Apple
   Item "American" Value 16
   Item "Mexican" Value 10

Group Grapes
   Item "Arabian" Value 25
   Item "Indian" Value 20

Group value3 .. 
   and so on

如果变量=='南瓜'我们在上面搜索Dict数据结构,因为它不存在南瓜,我们不打印任何东西

If variable == 'pumpkin' we search for it in the above Dict data structure and since it pumpkin is not present , we dont print anything

等..

我希望我能够解释一下我的想法。
注意:这更好地与上述问题合并,所以我也可以接受答案

I hope I am able to explain what my want. Note: It is better that this be merged with above question and so I can accept answers too

推荐答案

for i in dict.keys():
    print "Group", i
    for j in dict[i].keys():
        print "Item", j, "Value", dict[i][j]

这篇关于从python字典访问特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆