繁体   English   中英

Python 匹配给定列表中的字典

[英]Python match dictionary in given list

美好的一天,我在使用一个简单的脚本时遇到了一些错误。 我只需要从我的列表中打印汽车列表。 如果有人可以发表评论,将不胜感激。 谢谢。

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:
...

当您执行此操作时,您将 go 遍历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))

美好的一天,我在一个简单的脚本中遇到了一些错误。 我只需要从我的列表中打印汽车列表。 如果有人可以发表评论,将不胜感激。 谢谢。

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM