如何获取列表中嵌套字典的值?
问题描述:
我有一个小蟒蛇功能的问题,目前我有这样的结构:如何获取列表中嵌套字典的值?
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循环,但之后,我不知道我怎么能进入列表中包含字典和检索“数字”键的值。
如果你有答案,你能解释给我,我的意思是你怎么找到该怎么做。
感谢
答
一个简单的解决方案可能是只是遍历所有元素。
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')
答
这应做到:
print "You entered a valid number, it is:", dict_conf[conf_type][option][0]['number']
答
改造numbers
成一个列表,并检查进入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
答
这是完整的工作代码:
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'},...] – AChampion
没错。将价值作为词典而不是词典列表会更有意义。 – Barmar
你实际得到'conf_type'&'option'或'conf_type&number'是什么输入? – AChampion