Programming in Python

Hi, I am trying to teach myself python (which is going very slowly) and I have an assignment to do. Part of the assignment is asking me to read from a text file which contains a list of people's preferences for meals at a restaurant, eg. Bill - steak, fish, chicken; Mary - fish, chicken, steak; Joe - steak, chicken, fish. The assignment wants me to read from the file and then return the preferences as a dictionary. If anyone can help me with writing the code for this, I would be grateful.

Comments

  • reading in the file will depend on what format the data is in. If the data is in comma separted value format, you should check out the csv module. Otherwise, you can do something like:
    my_file = open('file_name')
    my_file will be a generator, so you will be able to get the next line in the file with
    line = my_file.next()
    you can also put this in a for loop:
    for line in my_file:
    #do stuff to each line

    from there, I believe my_file.next() will return a string, so you can do something like:
    output_dict = {}
    for line in my_file.next():
    output_dict.update(e.split())
    #that only works if e.split() returns 2 elements (ie, there are 2 elements on
    #a line. If there are more than 2 per line, consider storing e.split() and
    #munging the results into something useful

    Good luck!
  • Update, I totally missed the data sample you posted. It would be convenient store the second part as a list, so you have dict like
    { name: [food list] }

    This will require you to mess with the input from my_file.next(). Maybe this:
    out_dict = {}
    a = my_file.next().split() # split on spaces
    b = a[0] # first el is the name
    # second el is the dash
    c = a[2:] # slice the list so everything else goes is food
    out_dict.update([b,c])
    #or
    out_dict[b] = c

  • #!/usr/bin/env python
    import string
    my_file=open('test.txt')
    my_dict={}

    for eachline in my_file.readlines():
    #eachline=[w for w in re.sub(';','',eachline)]
    eachline=string.replace(eachline,';','')
    eachline=string.replace(eachline,',','')
    print eachline
    key=eachline.split()[0]
    #print key
    value=eachline.split()[2:]
    #print value
    my_dict[key]=value
    #my_dict.update([key,value])
    print my_dict

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories