Python: Dictionary key name that changes dynamically in a loop

10,271

Solution 1

You can use string formatting to create a string key with the current loop index

res = {}
for j in xrange(10):
    key_j = 'key_{}'.format(j)  # a string depending on j
    res[key_j] = j**2

The resulting res dictionary is:

{'key_5': 25, 'key_4': 16, 'key_7': 49, 'key_6': 36, 
 'key_1': 1, 'key_0': 0, 'key_3': 9, 'key_2': 4, 'key_9': 81, 
 'key_8': 64}

Note that dictionary keys are not ordered. If you want to keep the order, you need to use OrderedDict instead of regular dict.

BTW,
dictionary keys do not have to be strings, you can use int as keys as well (in fact every "hashable" object can be used as a key):

res = {}
for j in xrange(10):
    res[j] = j**2 # int as key

Resulting with:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

In this example the keys are ordered, but it is not guaranteed to be so.


Note that you can create res dictionary using dictionary comprehension, for example:

res = {j: j**2 for j in xrange(10)}

or

res = {'key_{}'.format(j): j**2 for j in xrange(10)}

Solution 2

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

Solution 3

this will wok simply,

for j in range(10):
    # since your key format is simple you can write in one line
    dict['key_%s'%j] = j**2 

Try to rename dict since it is type it is not good practice to use as variable name

Share:
10,271
Euler_Salter
Author by

Euler_Salter

Updated on June 15, 2022

Comments

  • Euler_Salter
    Euler_Salter almost 2 years

    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