Multi-value dictionary creation for a key

Asked

Viewed 1,277 times

0

I’m trying to create a code for registration by input, as an exercise.

dic = {}
    ...
def cadastrar():
   nome = input('Nome: ')
   variavel1 = input('variavel 1,: ')
   variavel2 = input('Variavel 2: ')
   dic.update({'nome': 'variavel1', 'variavel2'})

while True:
    opcao = exibirMenu()
    if opcao == ('cadastrar'):
        cadastrar()

this syntax error code, I change the code to:

dic.update('nome', 'varriavel1', 'variavel2')

and returns the error

Typeerror: update expected at Most 1 Arguments, got 2

how do I save the data together, nome = variavel1, variavel2. so that you can access the name and return the variables attached to the name?

1 answer

1


You can register a tuple. To create a tuple, the two variables must be wrapped in parentheses:

dic.update({'nome': (variavel1, variavel2)})

It is also important to remember that when referencing a variable, no quotation marks are used. 'variavel1' is a string constant whose value is 'variavel1', and not the value that really is in the variable 'variavel1'.

To access the values of the tuple in your dictionary, you would do so:

print(dic['nome'][0])  # variavel1
print(dic['nome'][1])  # variavel2
  • It worked out, thanks, buddy. Just one more question: would you be able to change the format of the data when returned by print? it returns thus: {'name': ('variable1', 'variable2', 'Nome2': ('variable3', 'variable 4')}) wanted to give an improved aesthetic, to look like this: Name: variable1, variable2. Name2: variable3, variable4. , or it would be better to create a database in mysql?

  • @You can create a function to show the data the way you want. When you use print in a dictionary, it comes out in a standardized way so you can know what kind of structure is inside it (for example, a list uses brackets and a tuple uses brackets). A database in mysql is a very different use case than a dictionary, and will depend on its need. In this case, it does not seem to be necessary.

  • Okay, Peter. I get it. With your help I managed to get past that part that was very difficult, I’m trying to get past a difficulty now in while and Else functions. in this my last message I think I mixed a little my doubts kkk. whether it was possible to edit the way the data was shown and whether it was better to save the input data in a database to be accessed and edited later. ex: users register item with color and weight variables and other users can access a list with items from all users. , if you can, take a look at the code https://pastebin.com/kWmHBT9C

Browser other questions tagged

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