'Iteratively adding new lists as values to a dictionary

I have created a dictionary (dict1) which is not empty and contains keys with corresponding lists as their values. I want to create a new dictionary (dict2) in which new lists modified by some criterion should be stored as values with the corresponding keys from the original dictionary. However, when trying to add the newly created list (list1) during every loop iteratively to the dictionary (dict2) the stored values are empty lists.

dict1 = {"key1" : [-0.04819, 0.07311, -0.09809, 0.14818, 0.19835],
         "key2" : [0.039984, 0.0492105, 0.059342, -0.0703545, -0.082233],
         "key3" : [0.779843, 0.791255, 0.802576, 0.813777, 0.823134]}
dict2 = {}

list1 = []


for key in dict1:
    if (index + 1 < len(dict1[key]) and index - 1 >= 0):
        for index, element in enumerate(dict1[key]):
            if element - dict1[key][index+1] > 0:
                list1.append(element)    

        dict2['{}'.format(key)] = list1

        list.clear()

print(dict2)

The output I want:

dict2 = {"key1" : [0.07311, 0.14818, 0.19835],
         "key2" : [0.039984, 0.0492105, 0.059342],
         "key3" : [0.779843, 0.791255, 0.802576, 0.813777, 0.823134]}


Solution 1:[1]

@timgeb gives a great solution which simplifies your code to a dictionary comprehension but doesn't show how to fix your existing code. As he says there, you are reusing the same list on each iteration of the for loop. So to fix your code, you just need to create a new list on each iteration instead:

for key in dict1:
    my_list = []
    # the rest of the code is the same, expect you don't need to call clear()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code-Apprentice