J Udin
J Udin

Reputation: 3

Checking dictionary value list for matches

Hello new to programming and python here. I'm trying to make a program that will take a list of keys and values; then add those items to a dictionary. The program should check each value against current values in a dictionary before appending it to the key. Here is my code so far.

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']}

Why did my final if statement not check the values already in the dictionary? And if there is a better way to do them please let me know. I know this community is filled will seasoned developers; but I am clearly not, so please take it easy on me. THANK YOU!

Upvotes: 0

Views: 60

Answers (2)

Nin17
Nin17

Reputation: 3502

You can make this more concise with dictionary and set comprehension:

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

Output:

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

Upvotes: 2

Piotr Grzybowski
Piotr Grzybowski

Reputation: 594

In your last if there should be:

if elements not in finalList[items]: rather than

if elements not in finalList.values():

Upvotes: 3

Related Questions