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.


  • 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 =
    you can also put this in a for loop:
    for line in my_file:
    #do stuff to each line

    from there, I believe will return a string, so you can do something like:
    output_dict = {}
    for line in
    #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 Maybe this:
    out_dict = {}
    a = # 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[b] = c

  • #!/usr/bin/env python
    import string

    for eachline in my_file.readlines():
    #eachline=[w for w in re.sub(';','',eachline)]
    print eachline
    #print key
    #print 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!