Home > Blockchain >  How do I take a dictionary from one function and use it in another in python?
How do I take a dictionary from one function and use it in another in python?

Time:03-10

Edit: changing code as the issue came up first somewhere else in my code

I'm trying to figure out how to use my dictionary from one function in another one and the other answers on here haven't helped.

The overall goal is to print the key and value just entered into the dictionary named contacts but contacts can only be defined inside init_phonebook

def init_phonebook():
contacts = {}
while True:
    choice = print_menu()
    if choice == 1:
        list_contacts(contacts)
    elif choice == 2:
        add_contact(contacts)
    elif choice == 3:
        find_contact(contacts)
    elif choice == 4:
        edit_contact(contacts)
    elif choice == 5:
        delete_contact(contacts)
    elif choice == 6:
        delete_all(contacts)
    elif choice == 7:
        thanks()

Down here the issue is that .keys and .values don't work as it's not recognizing contacts as a dictionary. I've tried changing the parameter to something else but it doesn't work that way either.

def add_contact(contacts):
    phone_number = input('Please enter a phone number: ')
    name = input('What would you like to save the name as?: ')
    if name in contacts:
        print('This contact already exists in your phonebook')
    elif name not in contacts:
        contacts[name] = phone_number
        print('Contact successfully saved')
        print('Your updated phonebook is shown below')
        for c in contacts:
            print('{} --> {}'.format(contacts.keys(c), contacts.values(c)))
    print()

the error message I get is:

File "c:\Users\myname\Desktop\VS Code Projects\contact_list.py", line 54, in add_contact print('{} --> {}'.format(contacts.keys(c), contacts.values(c))) TypeError: dict.keys() takes no arguments (1 given)

CodePudding user response:

The problem is not how you go about passing the dictionary to these other functions.The error actually arising within your add_contact() function, due to how you are trying to iterate through the dictionary key-val pairs:

 for c in contacts:
                print('{} --> {}'.format(contacts.keys(c), contacts.values(c)))

It seems you want to iterate through the contacts. contact.keys() does not let you access/index a key, this method returns all of the keys in a dict. contact.values does not let you access/index a value, it returns all of the values in the dict. When you call "for c in contacts", c represents a key. So here are two alternative ways to iterate through:

  1. Properly indexing on the contacts dict using the key c:
for c in contacts:    
    print('{} --> {}'.format(c, contacts[c]))
  1. By iterating through both the key and value pairs:
    for key,value in contacts.items():
      print('{} --> {}'.format(key, value))

If confused about a type in Python, I recommend referring to the documentation!

CodePudding user response:

dict.keys() and dict.values() both return arrays that can be indexed but accepts no inputs when called.

But in your case, since you are looping over the dictionary, each iteration stores the key in c. In your case that will be the name associated with the contact.

So you already have the key stored in c on each iteration. What you need next is to use the key to get the value like so dict[key] or dict.get(key).

Alternatively, you can loop over both keys and values simultaneously like so:

for name, phone_number in contacts:
   print("{} ==> {}".format(name, phone_number))

I am altering your original code as follows:


    def add_contact(contacts):
    phone_number = input('Please enter a phone number: ')
    name = input('What would you like to save the name as?: ')
    if name in contacts:
        print('This contact already exists in your phonebook')

    else: #You seem to have only two options so no need for elif
        contacts[name] = phone_number
        print('Contact successfully saved')
        print('Your updated phonebook is shown below')

        for c in contacts: #c will hold name in each iteration
            print('{} --> {}'.format(c, contacts[c]))




  • Related