To understand why your code doesn’t work, just make a table test, but anyway, let’s understand what happens.
The break'Those you put in interrupt the for more internal (what is iterating through the dictionary keys), then the for external will continue to iterate through all dictionaries. That is to say:
for dic in lista: # primeiro for
for cont, (key, value) in enumerate(dic.items()): # segundo for
if confirmar_cpf == value:
print(f'{cont} -> {key}: {value}')
break # este break interrompe o segundo for
else:
print('CPF NÃO ENCONTRADO!')
break # este break interrompe o segundo for
That is, in the first iteration of the first for, the variable dic will be the dictionary containing the CPF 123.456.789-10. Then he enters the second for, iterating through its keys, and finds the CPF (i.e., enters the if, prints the CPF and the break interrupts the second for, then he stops iterating for the keys to the dictionary).
But the break just interrupted the loop internal, however the loop not external, so it continues to iterate through the list. There in the second iteration dic will be the dictionary containing the CPF 123.456.789-11. The second for iterates by the keys of this, in the first iteration sees that the value is not equal to the CPF being searched and enters the else, printing "CPF NOT FOUND" message and the break interrupts the for intern.
And since the list only has two elements, the for external closes.
If the idea is to compare a specific key, do not need to iterate through all, just access it directly (in case, it would be dic['CPF'] to access the CPF value directly). And only if the CPF is found, then you iterate for the CPF keys:
cadastro_mec = [
{'CPF': '123.456.789-10', 'Nome': 'Guilherme Flavio', 'Data de Nascimento': '01/04/1989', 'Salário': 'R$1045.0',
'E-mail': '[email protected]', 'Telefone': '(19) 89765-4326'},
{'CPF': '123.456.789-11', 'Nome': 'Marco Machado', 'Data de Nascimento': '09/11/1990', 'Salário': 'R$1648.0',
'E-mail': '[email protected]', 'Telefone': '(11) 3665-4899'}]
confirmar_cpf = '123.456.789-10'
for dic in cadastro_mec:
if confirmar_cpf == dic['CPF']: # acessar o CPF diretamente
# se encontrou o CPF, aí sim imprime todas as chaves do dicionário
for cont, (key, value) in enumerate(dic.items()):
print(f'{cont} -> {key}: {value}')
break # interrompe o for externo
else:
print('CPF NÃO ENCONTRADO!')
Note that only if the number is found, I do the other for iterating through the dictionary keys. And inside the if has the break, which in this case interrupts the for external (because if I have already found the CPF, I no longer need to iterate through the rest of the list).
And the else is from for, and not of if (yes, in Python this is possible). In this case, he enters the else if the for nay is interrupted by a break. And how I only use break if you find the number, then it only goes into the else if the number is not found.