简体   繁体   中英

How to match dictionary value list items stored to items in a separate list?

I am trying to match list items to items in dictionary value which are stored as a list.

I have the following list:

new_list = ['apple', 'banana', 'orange']

and the following dictionary:

new_dict = {abc: ['apple', 'kiwi'], bca: ['strawberry', 'banana', 'mango'], dcf: ['watermelon', 'apple', 'starfruit']}

What I want to do is match items in new_list to the items that are in the dictionary value list.

This is what my code looks like:

final_list = []
for k,v in new_dict.items():
    for values in v:
        for items in new_list:
            if items in values:
               print k
               print items

I believe the above code is computationally heavy. Also, when the above code does provide some results, it only matches the list items to the first index in the value list. For example, even though the list item "banana" is in the 2nd key:value pair, it doesn't match it. Is there a way to match every item in the value list?

You have one too many for loops.

new_dict.items() returns the keys and the values for said keys, so you dont need to iterate through v

for k, v in new_dict.items():
    for items in new_list:
        if items in v:
            print items, k

Output:

apple abc
banana bca
apple def
>>>

This isn't computationally heavy, you WILL need to iterate through new_list and you will need to check if an item in new_list is in v .

Optimisation wise, you might want to sort your values in the dictionary so that less comparisons are needed to check if items in v but I doubt you'll see any significant increase in speed. Best way would be to have a nice and efficient structure for whatever it is that you are doing.

That being said, I'm fairly new to optimisation so please it take with quite a large pinch of salt.

Also lastly:

new_dict = {'abc': ['apple', 'kiwi'], 'bca': ['strawberry', 'banana', 'mango'], 'def': ['watermelon', 'apple', 'starfruit']} (syntax)

You can convert new_list to a set for more efficient lookups:

new_set = set(new_list)
for k, v in new_dict.items():
    for item in v:
        if item in new_set:
            print(k, item)

so that given:

new_list = ['apple', 'banana', 'orange']
new_dict = {'abc': ['apple', 'kiwi'], 'bca': ['strawberry', 'banana', 'mango'], 'dcf': ['watermelon', 'apple', 'starfruit']}

this outputs:

abc apple
bca banana
dcf apple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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