0

I am trying to create a list of 5 values using a loop. When the loop completes, the list needs to append to a dictionary key. Then I want to overwrite the old list with 5 new values and append the updated list to a different key in the dictionary.

Writing the keys to the dictionary is working fine, but something(s) mixed up with my lists. If I clear the swatch_list after writing it to the dictionary, it also deletes it from the dictionary and I end up with a dictionary that only contains keys. If I don't clear it, the list gets longer and longer and I end up with dozens of repeated values for each key rather than 5 unique ones. How can I create the list and reset it back to empty for each round without affecting the dictionary?

swatch_list = []            
        for y in range(0, 5):
            try:
                swatch = driver.find_element_by_xpath(
                f"/html/body/div[1]/div/div/div/div[1]/div[2]/div/div/div/div/div[1]/div[{str(x)}]/div[1]/div[1]/div[{str(y+1)}]")
            except:
                print("skip")
            finally:
                swatch_RGB = swatch.get_attribute("style")
                cleaned_RGB = swatch_RGB[swatch_RGB.find("(") + 1:swatch_RGB.find(")")]
                swatch_list.append(cleaned_RGB)

        try:
            themes_dict(card_theme_title).append(swatch_list)
            swatch_list.clear()

current output:

themes_dict = {A:[],B:[],C:[]}

desired output:

themes_dict = {A:[1,2,3,4,5],B:[6,7,8,9,10],C:[11,12,13,14,15]}
kellie A
  • 3
  • 4
  • You only have one list object created with `swatch_list = []` which you modify and most notably `clear()`. You’ll want to create some new, independent lists at some point. – deceze Feb 17 '21 at 07:01
  • use `copy()` method while appending since the object that is appended and the one that is cleared point to the same object, with `list.copy()` you create a copy and append that to the list. – Krishna Chaurasia Feb 17 '21 at 07:02
  • Thanks, I created a new list called value_list and set it equal to swatch_list.copy(), that helped – kellie A Feb 17 '21 at 19:26

0 Answers0