Jaakkath
Jaakkath

Reputation: 65

Python text file into dictionary not working

So the file text, which I'm supposed to transfer to a dictionary for a phonebook, looks like this:

Name1 Name2 Numbers

Name3 Name4 Numbers2

and so on..

What I've tried:

def read():

    file1=open("file.txt","r")

    dict={}

    for line in file1:

        line=line.split()

        if not line:continue

        dict[line[0]]=line[1:]

    print(dict)

When I run it, it prints nothing.

Thank you!

Upvotes: 2

Views: 196

Answers (4)

Philippe Oger
Philippe Oger

Reputation: 1098

Many comments to make here.

1 - You forgot to add ".read()" when you open your file.

2 - You re using reserved words for the python language. "dict" is something used by the language, so avoid using it directly. Instead name them more specifically. Avoid at all cost naming your variables with words already used by Python language.

3 - Your function does not return anything. At the end of each function, you need to specify "return" plus the object you want the function to return value.

def read_dict():
    file1 = open("file.txt","r").read()
    my_dict = {}
    for line in file1:
        line = line.split()
        if not line:
            continue
        my_dict[line[0]] = line[1:]
    return my_dict

print(read_dict())

Upvotes: 0

chandong83
chandong83

Reputation: 81

this is my way

def read_dict():
    file1 = open("file.txt", 'r')
    dict={}  

    # read lines of all
    lines = file1.readlines()

    # Process one line at a time.
    for line in lines:
        line = line.split()
        if not line: continue
        dict[line[0]] = line[1:]

    file1.close()
    print(dict)

read_dict()

or (use with) you don't have to close file

def read_dict():
    with open("file.txt", 'r') as file1:
        dict={}  
        # read lines of all
        lines = file1.readlines()
        # Process one line at a time.
        for line in lines:
            line = line.split()
            if not line: continue
            dict[line[0]] = line[1:]
        print(dict)

Upvotes: 1

Ajay Maity
Ajay Maity

Reputation: 760

You have included your implementation inside a function read(). You need to call the function somewhere.

def read():
  file1=open("file.txt","r")

  dict={}

  for line in file1:

    line=line.split()

    if not line:continue

    dict[line[0]]=line[1:]

  print(dict)

read()

Try this.

Upvotes: 0

sniperd
sniperd

Reputation: 5274

Make sure you call the function. I've changed a little of it around so it's not using words like 'read' or 'dict'. This works:

def main():
    thefile = open("file.txt","r")
    thedict={}
    for theline in thefile:
        thelist = theline.split(" ")
        if not thelist:
            continue
        thedict[thelist[0]]=thelist[1:]

    print(thedict)

main()

results in:

{'Name1': ['Name2', 'Numbers\n'], 'Name3': ['Name4', 'Numbers2']}

Upvotes: 0

Related Questions