Search code examples
pythonloopsdictionarykey

Python: Dictionary key name that changes dynamically in a loop


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


Solution

  • 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)}