我在Python中很新。 我必须找到/比较一个字符串值与列表中的字典列表中存在的列表。我编写了下面的代码,虽然它运行良好,但我们可以用更好的方式编写代码。如何在Python中List的字典列表中找到值?
abc = [{'GetDriverPackInfo_OUTPUT': {'OSList': [u'Linux', u'Windows', u'Xen', u'VMware'], 'ReturnValue': [u'0'], 'Version': [u'15.07.04']}}]
os_name = "Linux"
for k in abc: #['GetDriverPackInfo_OUTPUT']['OSList']:
if os_name in k['GetDriverPackInfo_OUTPUT']['OSList']: #== os_name:
print ("os_name found")
else:
print ("os_name not found")
确保每个外dict有关键'GetDriverPackInfo_OUTPUT'和每个内部字典都有键'OSList'?否则'if'语句可能会抛出异常 – Hooting
将abc总是有一个'GetDriverPackInfo_OUTPUT'? – fahad
@fahad:是'abc'将始终为'GetDriverPackInfo_OUTPUT' –