Python 如何获取列表中嵌套字典的值?
我遇到了一个小python函数的问题,目前我有以下结构:Python 如何获取列表中嵌套字典的值?,python,list,dictionary,nested,Python,List,Dictionary,Nested,我遇到了一个小python函数的问题,目前我有以下结构: dict_conf = {'conf_storage': {'option1':[ {'number':'20169800'}, {'name':'usb'}, {'description':'16gb'}, {'qty':'1'}, {'vendor=':
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")
我想找到“number”值,例如,如果用户输入:
conf_type = "conf_storage"
number = "20169800"
然后打印该值并显示一条消息:“您输入了一个有效的数字,它是:20169800”
我解决这个问题的想法是迭代并返回与用户输入值相等的每个值
如果我使用iteritems,我会得到每个元素,然后我可以将其放入for循环,但之后我不确定如何进入包含字典的列表并检索“number”键的值
如果你有答案,请你解释给我听,我是说你是如何找到该做什么的
谢谢这应该可以做到:
print "You entered a valid number, it is:", dict_conf[conf_type][option][0]['number']
将
编号
转换为列表,并检查输入的编号是否在列表中,例如:
conf_type = "conf_storage"
number = "20169800"
if number in [option[0]['number'] for option in dict_conf[conf_type].values()]:
print("You entered a valid number, it is: {}".format(number))
# You entered a valid number, it is: 20169800
一个简单的解决方案可能是迭代所有元素
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')
这是完整的工作代码:
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: ")
number = raw_input("Enter the number for validation: ")
dict_options = dict_conf[conf_type]
option_list = dict_options[option]
for elem_dict in option_list:
if 'number' in elem_dict.keys():
if elem_dict['number'] == number:
print "You entered a valid number, it is: " + number
为什么要列出单值词典`[{'number':'20169800'},{'name':'usb'},…]没错。将值设置为字典而不是字典列表更有意义。您实际获得的是什么输入conf_type
&option
或conf_type&number
?从哪里获得option
变量?原始输入。。。看看原始的姿势,OP显示为输入的内容与代码中显示的内容不一致。