Home > Enterprise >  Iteratively adding new lists as values to a dictionary
Iteratively adding new lists as values to a dictionary

Time:03-05

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]}

CodePudding user response:

The problem is that list always refers to the same list, which you empty by calling clear. Therefore all values in the dict refer to the same empty list object in memory.

>>> # ... running your example ...
>>> [id(v) for v in dict2.values()]
[2111145975936, 2111145975936, 2111145975936]

It looks like you want to filter out negative elements from the values in dict1. A simple dict-comprehension will do the job.

>>> dict2 = {k: [x for x in v if x > 0] for k, v in dict1.items()}
>>> 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]}

CodePudding user response:

@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()
  • Related