How to popular a dynamically key and value dictionary?

Asked

Viewed 220 times

3

Write a program that takes an integer n value and returns a dictionary where the keys are numbers from 1 to n and the values are the squares of their respective keys.

Ex: for n = 8, the result should be {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}.

My attempt:

n = int(input("Digite o valor de n:"))

list = []

for x in range(1,n+1):

  list.append(x**2)

print(list)

However, I couldn’t put this list in dictionary mode.

3 answers

4

You declared a list and not a dictionary. Dictionary is declared with {}

n = int(input("Digite o valor de n:"))

dicionario = {}

for x in range(1,n+1):

  dicionario[x] = x ** 2

print(dicionario)

4

To resolve this issue you must implement a dictionary - whose delimiters are {} - and not a list - whose delimiters are [].

One of the ways you can use it is Dictionary comprehensions PEP 274.

Using this technique we can assemble the following code:

n = int(input("Digite o valor de n: "))
dicionario = {i: i ** 2 for i in range(1, n + 1)}

print(dicionario)

Note that when we execute this code we must enter an integer number and press Enter.

From that moment on the block for will go through the range(1, n + 1) and for each interaction, will be added i by key and the square of i to the value of the key.

Later the dictionary will be displayed properly mounted.

Testing the code

Imagine we want to list the 8 perfect first squares. For this, when executing the code we must enter...

8

...and then press Enter.

Immediately the code will perform the calculations and display us as a result:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

3

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.