The dictionary defines an injection relationship between the keys and the values. In practice, this implies that the key of a dictionary must be unique and related to only one value (the opposite is not valid since a value can be associated with more than one key).
See 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 . 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.
Therefore, the {'r': '3', 'r': '5'}
output you want can not be obtained - not with standard dictionary at least. But since the statement does not require the key to be duplicated, just that it is possible to associate multiple values with a key, you can create a list to store the values.
Also, regarding your solution, I find it a bit uncomfortable for the user to have to enter the key every time they want to enter a new value. You can here define two repeat loops to read the values of each key indefinitely.
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, I would stay:
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 still use some variations of the dictionary, such as collections.defaultdict
. to set the default value type if it does not exist in the dictionary.
Notice that I used Enter itself to end each loop because the key / value pair {'q': 'q'}
is probably perfectly valid within the dictionary.