Python: Dictionary key name that changes dynamically in a loop

Viewed 11924

My minimal working example is the following: I have a loop iterating a certain number of times. At each iteration, I would like to create a new key with a name depending on the current index value, for instance key_j, and assign a certain value to it. Is there a way to do this?

for j in range(10):
    dict[key_j] = j**2

Thank you

3 Answers

You can use pythons f strings to generate keys based on the index and then use these keys to create dictionary as follows

my_dict = {}
for j in range(4):
  key = f'key_{j}'
  my_dict[key] = j**2
  
print(my_dict)
#{'key_0': 0, 'key_1': 1, 'key_2': 4, 'key_3': 9,}

Related