Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 342
Euler_Salter Avatar asked Jul 03 '17 08:07

Euler_Salter


People also ask

How do I create a dynamic nested dictionary in Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

Can dictionary keys be changed Python?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

Can Python dictionary float a key?

There's no problem using floats as dict keys. Just round(n, 1) them to normalise them to your keyspace.


3 Answers

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)}
like image 112
Shai Avatar answered Oct 13 '22 00:10

Shai


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

like image 29
DexJ Avatar answered Oct 13 '22 00:10

DexJ


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,}
like image 2
Hadi Mir Avatar answered Oct 12 '22 23:10

Hadi Mir