Create a key/value association from user-informed data

Asked

Viewed 59 times

3

8) Write an algorithm capable of receiving a variable amount of parameters that are associated with a key. Then print on the screen the name of the key and its value:

def func_varios_parametros_dic(**dicionario):
    print(dicionario)

lista_k = []
lista_v = []
x = 0

while True:
    lista_k.append(input("Informe a chave[q em ambos p/ sair]: "))
    lista_v.append(input("Informe o valor[q em ambos p/ sair]: "))
    if (lista_k[x] != 'q' and lista_v[x] != 'q'):
        func_varios_parametros_dic(**dict(zip(lista_k, lista_v)))
        x += 1
    else:
        break

It works normal, but if I type for example r in key and 3 in the value, the output is like this:

{'r': '3'}

and then type in r again in the key and 5 in the value, the exit looks like this:

{'r': '5'}

and what I want is for it to stay that way:

{'r': '3', 'r': '5'}

that is, if I type a key repeated, in the case of the letter r, it is superscripted together with its value 5. I’m not sure why not be printed on the screen the pair key/value even if they are repeated.

  • 3

    The result {'r': '3', 'r': '5'} will not be possible. The dictionary is a map that defines a 1:1 relation between key/value. There is no way the same key has two values. The most you can do is something like {'r': ['3', '5']}, where the value is a list of values informed by the user.

  • Just thinking about the concept of key, which is unique. that’s why Voce is having this problem using Dict

1 answer

4


The dictionary defines an injecting relationship between keys and values. In practice, this implies that the key of a dictionary must be unique and related to only one value (otherwise it is not valid, as a value may be associated with more than one key).

Vide official language documentation:

It is best to think of a Dictionary as a set of key: value pairs, with the requirement that the Keys are Unique (Within one Dictionary). A pair of braces creates an Empty Dictionary: {}. Placing a comma-separated list of key:value pairs Within the braces adds initial key:value pairs to the Dictionary; this is also the way Dictionaries are Written on output.

So the way out {'r': '3', 'r': '5'} that you want is not possible to get - not with default dictionary at least. But since the statement does not ask for the key to be duplicated, only that it is possible to associate multiple values to a key, you can create a list to store the values.

Also, regarding your solution, I find it a little uncomfortable for the user to have to enter the key every time they want to enter a new value. You can here set two repeat loops to read indefinitely the values of each key.

dicionario = {}

while True:
    chave = input('Entre com a chave [enter para sair]: ')
    if not chave:
        break
    if chave not in dicionario:
        dicionario[chave] = []
    while True:
        valor = input(f'Entre com o valor para a chave {chave} [enter para sair]: ')
        if not valor:
            break
        dicionario[chave].append(valor)

print('Seu dicionário final é:')
print(dicionario)

So it would be:

Entre com a chave [enter para sair]:  a
Entre com o valor para a chave a [enter para sair]:  1
Entre com o valor para a chave a [enter para sair]:  2
Entre com o valor para a chave a [enter para sair]:  
Entre com a chave [enter para sair]:  b
Entre com o valor para a chave b [enter para sair]:  1
Entre com o valor para a chave b [enter para sair]:  
Entre com a chave [enter para sair]:  
Seu dicionário final é:
{'a': ['1', '2'], 'b': ['1']}

You can also use some variations of the dictionary, such as collections.defaultdict to set the default type of the value if it does not exist in the dictionary.

Understand that I used my own Enter to finish each loop because probably the key/value pair {'q': 'q'} is perfectly valid within the dictionary.

Browser other questions tagged

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