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.
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.– Woss
Just thinking about the concept of key, which is unique. that’s why Voce is having this problem using Dict
– Clayton Tosatti