0

I have this code as example:

list100 = [1, 1, 1]
list200 = [2, 2, 2]
save_dict = dict()
for i in [100, 200]:
   save_dict[i] = 'list' + str(i)

Now save_dict will be {100: 'list100', 200: 'list200'}.

What I want is {100: [1, 1, 1], 200: [2, 2, 2]}.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Why do you need to do this? – matszwecja Jan 20 '22 at 15:42
  • 4
    Why not just `lists = {100: [1, 1, 1], 200: [2, 2, 2]}`? What I mean is, using strings to access variables by name is a code smell and you should rethink your problem statement to avoid this. – 0x5453 Jan 20 '22 at 15:47
  • 1
    I do not know how to explain why I need this. A long story. First I will generate a lot of numpy arrays around 2000. Then I want to use numpy.savez to store them in a single file. Therefore I need to put these 2000 lists into a dictionary but I do not find a good way to do this. – MarsEclipse Jan 21 '22 at 06:38

1 Answers1

1

you can use globals for this:

list100=[1,1,1]
list200=[2,2,2]
save_dict = dict()
for i in [100, 200]:
   save_dict[i]=globals()[f'list{i}'] #brings the global variable that is assigned of `f'list{i}'`
XxJames07-
  • 1,833
  • 1
  • 4
  • 17