-2
I was wondering if I could create a dictionary using loops. But I don’t want to create a dictionary within a list [{ }].
example:
from random import randint
jog = dict()
for n in range(1, 5):
jog['Numb'] = randint(0, 6)
print(jog)
-2
I was wondering if I could create a dictionary using loops. But I don’t want to create a dictionary within a list [{ }].
example:
from random import randint
jog = dict()
for n in range(1, 5):
jog['Numb'] = randint(0, 6)
print(jog)
3
Yes, it’s possible and your code already does that.
However, as commented, because you always assign the same key in the dictionary, you will always be overwriting the old value. This way, your exit will always be something like {'Numb': 6}
, where 6 in this example has been defined randomly.
If the idea is to store all values in different keys, you could concatenate the value of n
, which is its iteration variable, to generate unique keys:
from random import randint
jog = dict()
for n in range(1, 5):
jog[f'Numb-{n}'] = randint(0, 6)
print(jog)
So the exit would be something like:
{'Numb-1': 1, 'Numb-2': 3, 'Numb-3': 1, 'Numb-4': 0}
Still, using the syntax of Dict comprehension, you can simplify into a line of code:
jog = {f'Numb-{n}': randint(0, 6) for n in range(1, 5)}
Producing an equivalent result.
Thank you very much, now I understand much better.
Browser other questions tagged python list loop for dictionary
You are not signed in. Login or sign up in order to post.
Yes, but there can be repeated keys, in this case 'Numb' will get the last assigned value
– Miguel