-1

This is what I have so far, right now I get sankey is not defined.

    def makeSankey (inf):

     sankey = {}
     with open("file.txt") as f:
         for line in f:
            (key, val) = line.split()
            sankey[str(key)] = val



     return makeSankey()

    for i in sankey():
     print(i),sankey[i]`

The text file looks like this:

    Single,2106
    Double,603
    Triple,44
    Home Run,431
    Walk / HBP,1402
    Sacrifice Out,137
    Other Out,8160
dsh
  • 12,037
  • 3
  • 33
  • 51
MrPuffy
  • 1
  • 1

2 Answers2

1

First of all, you can't access sankey outside the function. You can't call sankey as it's not your function's name which is makeSankey. What you meant to do with return makeSankey was probably return the value, which is stored in sankey so you return sankey.

Your code in fixed condition should be something like this, I still am not sure about the input if it's the same as you provided but you can try it:

def makeSankey(fileName):
    sankey = {}
    with open(fileName) as f:
        for line in f:
            (key, val) = line.split()
            sankey[key] = val
    return sankey

data = makeSankey("file.txt")

for i in data:
    print(i, data[i])
Guven Degirmenci
  • 684
  • 7
  • 16
0

This works if file.txt contains lines like key,val. use python script.py file.txt

#!/usr/bin/python2
import sys

def makeSankey(file_name):
    sankey = {}
    with open(file_name) as f:
        for line in f:
            (key,val) = line.split(",")
            # strip to remove \n
            sankey[key] = val.strip()

    # return the dic to the caller
    return sankey

if __name__ == "__main__":
    # received file name as an argument, if not then just pass it to makeSankey fun
    sanKeyDic = makeSankey(sys.argv[1])
    print(sanKeyDic)
alshaboti
  • 643
  • 8
  • 18
  • Can you explain why this works and OP's does not? I.e. explain why return sankey is required rather than returning the function call – RNHTTR Dec 04 '19 at 22:46
  • I fixed up my code but I am receiving this error: FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'. I will add in all my other code to show you. I want the name of the file to be provided as a command line argument. I am using IDLE 3 btw. – MrPuffy Dec 06 '19 at 18:55
  • Use `sys.argv` to read the arguments `argv[0]` is the name of the program itself, `argv[1]` is the name of the first argument, file.txt in this case. check the code up. – alshaboti Dec 07 '19 at 00:05