python - 如何获取列表内嵌套字典的值?

标签 python list dictionary nested

我在使用一个小的 python 函数时遇到问题,目前我有这个结构:

dict_conf = {'conf_storage':
            {'option1':[
                {'number':'20169800'},
                {'name':'usb'},
                {'description':'16gb'},
                {'qty':'1'},
                {'vendor=':'XLR'},
                {'online':'Yes'}],
            'option2':[
                {'number':'20161789'},
                {'name':'hardrive'},
                {'description':'128gb'},
                {'qty':'1'},
                {'vendor=':'KBW'},
                {'online':'NO'}]},
        'conf_grph':
                {'option1':[
                    {'number':'20170012'},
                    {'name':'HD_screen'},
                    {'description':'1080p'},
                    {'qty':'1'},
                    {'vendor=':'PWD'},
                    {'online':'Yes'}]}}

conf_type = raw_input("Enter the conf type: ")
option = raw_input("Enter the option")

我想找到“数字”值,例如,如果用户输入:

conf_type = "conf_storage"
number = "20169800"

然后打印该值和一条消息:“您输入了一个有效的数字,它是:20169800”

我解决这个问题的想法是迭代并返回与用户输入的值相等的每个值。

如果我使用 iteritems,我会得到每个元素,然后我可以将其放入 for 循环中,但之后我不确定如何进入包含字典的列表并检索“number”键的值。

如果您有答案,请您向我解释一下,我的意思是您如何找到该做什么。

谢谢

最佳答案

一个简单的解决方案可能是迭代所有元素。

conf_type = "conf_storage"
number = "20169800"

if dict_conf[conf_type]:
    for key, value in dict_conf[conf_type].items():
        for v in value:
            for k,num in v.items():
                if num == number:
                    print('found')

关于python - 如何获取列表内嵌套字典的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337170/

相关文章:

python - 更改实体的键名

python - 为什么变量 YourName = input ("What is your name?") 打印用户输入问题而不是用户输入

java - 将Java中的addAll函数制作一个副本

python - 如何将整数列表加入一个整数python

python - Stripe : Error "This application is not authorized to edit this account" while updating the account in stripe

python - Keras:监视另一个回调的输出的 ModelCheckpoint

python - 如何将具有定义值的字典键添加到列表中

python - 展平任意深度的字典

java - 根据键和值对映射进行排序

sorting - 是否可以在 Julia 中对字典进行排序?