0

I have a file with a bunch of names and emails. They are written as follows:

name
email
name
email

I cant figure out how to open the file and read line by line to where it pairs "name to email" in my dictionary

I got the code to work when I manually type in the names/emails into the dictionary but I need to pull it from the file.

LOOK_UP=1
ADD= 2
CHANGE= 3
DELETE=4
QUIT=5

def main():
    emails={}
    with open('phonebook.in') as f:
        for line in f:
            (name, email)=line.split
            emails[name]=email
        
        
    
    choice=0
    while choice !=QUIT:
        choice= get_menu_choice()
        if choice == LOOK_UP:
            look_up(emails)
        elif choice == ADD:
            add(emails)
        elif choice == CHANGE:
            change(emails)
        elif choice == DELETE:
            delete(emails)
    
def get_menu_choice():
    print('Enter 1 to look up an email address')
    print('Enter 2 to add an email address')
    print('Enter 3 to change an email address')
    print('Enter 4 to delete an email address')
    print('Enter 5 to Quit the program')
    print()
    choice= int(input('Enter your choice: '))

    while choice <LOOK_UP or choice >QUIT:
        choice= int(input('Enter a valid choice'))
    return choice
def look_up(emails):
    name= str(input('Enter a name: '))
    value=(emails.get(name, 'Not found.'))
    print(value)
    print()
    
def add(emails):
    name= str(input('Enter a name: '))
    emailsaddy= input(' Enter a email address: ')

    if name not in emails:
        emails[name]= emailsaddy
        print()
    else:
        print('That contact already exists')
        print()
def change(emails):
    name=str(input ('Enter a name: '))
    if name in emails:
        emailsaddy= str(input(' Enter a new email: '))
        emails[name]= emailsaddy
    else:
        print('That contact does not exist')
def delete(emails):
    name=str(input ('Enter a name: '))

    if name in emails:
        del emails[name]
    else:
        print('That contact is not found')
main()
    
  • This page has several solutions that will work for you: https://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python – jdaz Jun 23 '20 at 03:39

2 Answers2

0

Do something like this, every name line goes in if statement, and every email line goes in else and add to directory.

emails = {}
i = 0
with open('phonebook.in') as f:
    for line in f:
        if i == 0:
            name = line
            i = 1
        else:
            email = line
            emails[name] = email
            i = 0
thisisjaymehta
  • 614
  • 1
  • 12
  • 26
0
with open('phonebook.in') as f:
    # convert file into list
    pb = f.readlines()
    # pair off elements into (name, email) tuples, and construct a dict from them
    emails = dict(zip(pb[0::2], pb[1::2]))

See this answer for an explanation, in case that idiom is hard to understand

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53