Search code examples
pythondictionarytxt

How take data for dictionary from txt file (Python)


I had stuck with one menu option in my work, is there is somebody who know how to convert a data from a txt file into dictionary format?

The task is by menu option number 5 download data thet was made into txt file, and than, if the program was restart, and the data is lost (the code itself by default contains some data in the dictionary, but data from the previous program launch should be added to them if the menu item number 6 was selected)

The sample code I used is below, but it doesn't work

  if menu == 6:
       with open ('telephone.txt', 'r') as fr:
            for line in fr.readlines():
                name, num = line.split(',')
                telephone_dict[name] = [num]
                print(line)
        fr.close()

The whole code have a look like

telephone_dict = {"Nino":"0123", "Nick": "0234", "Jake":"0345"}
menu = 1

while menu !=0:
    print("""
1. Add new names and telephone numbers to the dictionary
2. Delete telephone numbers from the dictionary by the given name
3. View the entire telephone dictionary (names and numbers)
4. View/Search for a single entry by name

5. Save Data
6. Load Data

0. Exit
""")
    menu = int(input("Choose menu option: "))
      
    if menu == 1:
        name =(str(input("Enter a name: ")))
        num = (input("Enter a number: "))
        telephone_dict[name] = num
    
    if menu == 2:
        name = input("Name: ")
        if name in telephone_dict:
            del telephone_dict[name]
            print(name, "was deleted")  
        else:
            print(name, " - was not found")
            
    if menu == 3:
        for x in telephone_dict.keys():
            print("Name: ", x, "\tNumber:", telephone_dict[x])
        print()

    if menu == 4:
        name = input("Name: ")
        if name in telephone_dict:
            print("The number is", telephone_dict[name])
        else:
            print(name, "was not found")

    if menu == 5:
        file = open('telephone.txt', 'w')
        for x in telephone_dict.keys():
            a=( x + " " + telephone_dict[x] + '\n')
            file.write(a)
        file.close()

    if menu == 6:
        with open ('telephone.txt', 'r') as fr:
            for line in fr.readlines():
                name, num = line.split(',')
                telephone_dict[name] = [num]
                print(line)
        fr.close()
        
    if menu ==0:
        break
    

Solution

  • if menu == 6:
        with open ('telephone.txt', 'r') as fr:
            for line in fr.readlines():
                name, num = line.split()
                telephone_dict[name] = num
                print(line)
        fr.close()
    

    you don't need to split by comma , and remove [] num