'Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want)

   contact_emails = {

         'Sue Reyn' : '[email protected]',
         'Mike Filt': '[email protected]',
         'Nate Arty': '[email protected]'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)

The output I want is

[email protected] is Sue Reyn
[email protected] is Mike Filt
[email protected] is Nate Arty
[email protected] is Alf

the output I get it

Alf is [email protected]
Alf is [email protected]
Alf is [email protected]
Alf is [email protected]

What am I doing wrong? How should I fix this code to make it output what I would like it to output?



Solution 1:[1]

for contact in contact_emails:
    print(new_contact + ' is ' + new_email)

You are printing the new contact again and again. What you need to do is something like this:

for contact, email in contact_emails.items():
    print(email + ' is ' + contact)

This iterates all the key, value pairs of your dictionary.

Solution 2:[2]

instead of using this

contact_emails[new_contact] = new_email

try this

contact_emails.update({new_contact:new_email})

for key,val in contact_emails.items():
    print(key +' is ' + val)

Solution 3:[3]

You’re iterating over each contact in contact_emails, but the variable contact doesn’t appear in the print call. You can access the email using the name held in contact:

...
for contact in contact_email:
    print(contact_email[contact], 'is', contact)

Remember that new_email and new_contact are assigned outside of the loop so do not change on each iteration.

Solution 4:[4]

Learn more about iterating the dictionaries here - How to Iterate Through a Dictionary in Python

contact_emails = {
    'Sue Reyn' : '[email protected]',
    'Mike Filt': '[email protected]',
    'Nate Arty': '[email protected]'
    }

new_contact = input()

new_email = input()
contact_emails[new_contact] = new_email

for contact in contact_emails:
            print(contact_emails[contact]+ ' is ' + contact)

Output:

>>Alf
>>[email protected]
[email protected] is Sue Reyn
[email protected] is Mike Filt
[email protected] is Nate Arty
[email protected] is Alf

Solution 5:[5]

This is what ended up working for my little brain.

for contact, email in contact_emails.items():
    print('{} is {}'.format(email, contact))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jignatius
Solution 2 Jasper Nichol M Fabella
Solution 3 N Chauhan
Solution 4 Sundeep Pidugu
Solution 5 Jared Stokes