Skip to content
Advertisement

Check for string in list items using list as reference

I want to replace items in a list based on another list as reference.

Take this example lists stored inside a dictionary:

dict1 = {
   "artist1": ["dance pop","pop","funky pop"],
   "artist2": ["chill house","electro house"],
   "artist3": ["dark techno","electro techno"]
}

Then, I have this list as reference:

wish_list = ["house","pop","techno"]

My result should look like this:

dict1 = {
   "artist1": ["pop"],
   "artist2": ["house"],
   "artist3": ["techno"]
}

I want to check if any of the list items inside “wishlist” is inside one of the values of the dict1. I tried around with regex, any.

This was an approach with just 1 list instead of a dictionary of multiple lists:

check = any(item in artist for item in wish_list)
    if check == True:
        artist_genres.clear() 
        artist_genres.append()

I am just beginning with Python on my own and am playing around with the SpotifyAPI to clean up my favorite songs into playlists. Thank you very much for your help!

Advertisement

Answer

A regex is not needed, you can get away by simply iterating over the list:

wish_list = ["house","pop","techno"]
dict1 = {
   "artist1": ["dance pop","pop","funky pop"],
   "artist2": ["chill house","electro house"],
   "artist3": ["dark techno","electro techno"]
}

dict1 = {
   # The key is reused as-is, no need to change it.
   # The new value is the wishlist, filtered based on its presence in the current value
   key: [genre for genre in wish_list if any(genre in item for item in value)]
   for key, value in dict1.items() # this method returns a tuple (key, value) for each entry in the dictionary
}

This implementation relies a lot on list comprehensions (and also dictionary comprehensions), you might want to check it if it’s new to you.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement