Python匹配给定列表中的字典



你好,我有一些错误与一个简单的脚本。我只需要从我的列表中打印出汽车列表。如果有人能评论的话,我将不胜感激。谢谢。

mylist = ['mango','apple','tesla','honda']
vdict = {'car':['honda','nissan','tesla'],'fruits':['banana','apple','mango']}
result = None
for vdict in mylist:
if vdict['car'] == mylist:
result = vdict
print(str(result))

我会尽力解释,但是你的例子有点令人困惑。

你犯的第一个错误是将迭代值赋给vdict字典中同名的变量。

...
vdict = {'car':['honda','nissan','tesla'],'fruits':['banana','apple','mango']}
...
for vdict in mylist:
...

当你这样做时,你将遍历mylist列表中的所有值,并且每次迭代的值将分配给vdict,从而覆盖同名字典。

mylist = ['mango','apple','tesla','honda']
vdict = {'car':['honda','nissan','tesla'],'fruits':['banana','apple','mango']}
result = None
# So we will go through your mylist list and assign 
# the value of each iteration to the variable car.
for car in mylist:
# The code below checks whether the value of car (which is the iterated item) 
# is contained in the car value key in your dictionary.
if car in vdict['car']:  # If we use = instead of in, the value contained in car must be identical to the value contained in your dictionary in the car key
# Below, we assign the value contained in the car key of 
# your dictionary to the result variable if the above condition is true.
result = vdict['car']
print(str(result))

相关内容

  • 没有找到相关文章