0

I am trying to make a contact list/phone book in python 3.10 with a dictionary and list and have been trying to add a feature to add a searched contact that isn't inside of the phone book. The current method I am trying gives me "Runtime Error: dictionary changed size during iteration", so do I need to find a way to append the dictionary without a for loop, or does anyone have any suggestions? I'm sorry if this is simple or I make little since, I am just starting to independently learn how to code. Thank you for any help provided. Here's the part where the error comes from:

 from collections import defaultdict
 
 #contact list using collection module
 book = defaultdict(list)


 search = input('Enter the name of the person you are looking for: ')
                 for key, value in book.items():
                     if key.startswith(search):
                         print(key, value)
                     else:
                         new_contact = input('That person is not in your contacts. Would you like to add them?(yes = y and no = n)')
                         if new_contact == 'y':
                             add_info = input('What is their contact information?')
                             book[search].append(add_info)
                         else:
                             break
 


1 Answers1

0

Assuming you've a dictionary book existing like this **book** = {'Alex' : 1234, 'Jane': 5694, ...} This should help:

Generally it's not a good idea to loop an iterable (list, dictionary) and changing the data.

book = {'Bill': 3456, 'Jane': 1298}

search = input('Enter the name of the person you are looking for: ')
if search in book:  
    # found it   - if type either "Bill" or "Jane"
    print(search, book[search])
        
else:  # anything else - not in the phonebook.
    print(f'The {search} is not in the book')
    
    action = input('That person is not in your contacts. Would you like to add them?(yes = y and no = n)')
    
    if action == 'y':
        add_info = input('What is the contact information? (name phone) ')
        name, phone = add_info.split()
        #book[name].append(phone)  # this Won't work. "Missing key"!
        book.get(name, phone)
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
  • 1
    Sorry I should have included how the dictionary is set up. I am using the collections module with defaultdict, '''from collections import defaultdict book = defaultdict(list)''' Thank you for letting me know that it's not a good idea to loop an iterable. I'll remember that going forward. – Blake Redd May 31 '22 at 23:02
  • @BlakeRedd - if this post ever helps you, can you check/accept so this question is considered `Closed` now? – Daniel Hao May 31 '22 at 23:13