检查匹配项的字典值列表

Checking dictionary value list for matches

编程新手您好,这里是 python。我正在尝试制作一个程序,该程序将采用键和值列表;然后将这些项目添加到字典中。在将每个值附加到键之前,该程序应根据字典中的当前值检查每个值。到目前为止,这是我的代码。

finalList= {'turtle':['turtle10']}

keyList = ['turtle','cat','mouse','dog']
valueList =['turtle1','turtle2','turtle1','cat1','cat2','dog','dog1']
for i in keyList:
    finalList[i]= []

 for items in finalList.keys():
    #print('***Keys***'+items)
     for elements in valueList:
         #print('***Values***'+elements)
         res = not any(finalList.values())
         if items in elements:
            
             if elements not in finalList.values():
                finalList[items].append(elements)

            
            
        

    

print(finalList)




Output = {'turtle': ['turtle1', 'turtle2', 'turtle1'], 'cat': ['cat1', 'cat2'], 'mouse': [], 'dog': ['dog', 'dog1']}

为什么我最后的 if 语句没有检查字典中已有的值?如果有更好的方法,请告诉我。我知道这个社区充满了经验丰富的开发人员;但我显然不是,所以请放轻松。谢谢!

在你的最后一个如果应该有:

if elements not in finalList[items]: 而不是

if elements not in finalList.values():

你可以用字典和集合推导来让它更简洁:

finalList = {i : list({j for j in valueList if i in j}) for i in keyList} #Actually a dictionary but whatever

输出:

{'turtle': ['turtle1', 'turtle2'],
 'cat': ['cat2', 'cat1'],
 'mouse': [],
 'dog': ['dog', 'dog1']}