Home > database >  Initializing a dictionnary with a for loop
Initializing a dictionnary with a for loop

Time:10-21

I would like to initialize my dictionary res with empty vectors 'W1':[], 'W2':[] up to 100, but I don't know how to iterate on the i value.

res = {'lambda' : []} for i in range(0,99): res.update('W'{i 1}: [])

then later in my code, I have the same problem when I want to add to each of these 100 vectors a value.

for i in range(0,99): res['W'{i 1}].append(W[i])

Thank you!

CodePudding user response:

This will create a dictionary with 100 items (W0 - W99), all being a key to an empty list.

{"W"   str(i): [] for i in range(100)}

CodePudding user response:

You can try something like this.

res = {}
keys = 100
for i in range(1, keys 1):
    res.update({f'W{i}': []})

print(res)

Output

{'W1': [], 'W2': [], 'W3': [], ...
  • Related