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. The string "house" is inside artist[0] (and also artist[1]) so both items from the list should be removed and exchanged by the string "house" as value inside the list.
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!
CodePudding user response:
The idea is like this,
dict1 = { "artist1" : ["dance pop","pop","funky pop"],
"artist2" : ["house","electro house"],
"artist3" : ["techno","electro techno"] }
wish_list = ["house","pop","techno"]
dict2={}
for key,value in dict1.items():
for i in wish_list:
if i in value:
dict2[key]=i
break
print(dict2)
CodePudding user response:
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.