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
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.
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.
There's no problem using floats as dict keys. Just round(n, 1) them to normalise them to your keyspace.
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)}
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
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,}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With