By following his reasoning it is still possible to arrive at the intended result.
What your code lacked was just enumerating the list of squares obtained and building the dictionary on top of that enumeration.
To enumerate a everlasting use the built-in method enumerate(iterable, start=0)
that returns an enumerated object that is only a set of tuples pairs where each element of the tuple has the structure (n + start, iterable[n])
, where n
is an index of the element within the eternal.
To create a dictionary use the built-in method dict()
that can from a sequence of pairs create a dictionary.
#Faz o tratamento de exceções caso o usuário digite algo que não seja um número.
while(True):
try:
n = int(input("Digite o valor de n:"))
break;
except:
pass
l = []
for x in range(1,n+1):
l.append(x**2)
d = dict(enumerate(l,start=1))
print(d)
#Digite o valor de n:8
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Note that I changed the name of your list to l
because in python there is an embedded function whose identifier is list()
and when you overwrite your code loses its functionality.
Other ways to get the same result:
Using a Generator:
while(True):
try:
n = int(input("Digite o valor de n:"))
break;
except:
pass
g = (x**2 for x in range(1, n+1))
d = dict(enumerate(g, start=1))
print(d)
#Digite o valor de n:10
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Using the method zip()
and map()
:
#Faz o tratamento de exceções caso o usuário digite algo que não seja um número.
while(True):
try:
n = int(input("Digite o valor de n:"))
break;
except:
pass
z = zip(r:= range(1, n+1), map(lambda x:x**2, r))
d = dict(enumerate(z, start=1))
print(d)
#Digite o valor de n:20
#{1: (1, 1), 2: (2, 4), 3: (3, 9), 4: (4, 16), 5: (5, 25), 6: (6, 36), 7: (7, 49), 8: (8, 64), 9: (9, 81), 10: (10, 100), 11: (11, 121), 12: (12, 144), 13: (13, 169), 14: (14, 196), 15: (15, 225), 16: (16, 256), 17: (17, 289), 18: (18, 324), 19: (19, 361), 20: (20, 400)}
Ahh, I get it!! Thank you very much!
– LARICY EMMANUELLY DA SILVA FER