1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Rep Power

    Question Help with dictionaries and lists!

    Hello! This is my third week in Python and my knowledge is still close to 0! Not to mention, I get confused with C so, so much!

    I need some help with the following task:

    Write a function readEntry that takes a string of the form NAME:AGE and returns a dictionary of
    the form "name":NAME, "age": AGE where NAME is a string and AGE is an integer.

    So far I got this:

    def readEntry(s): 
                   info = {}  
                   info["name"] = name 
                   info ["age"] = age  
                   return info  
             if s <= ':':   
                  return str(name) 
             else s => ':':   
                  return int(age);
    I was actually going to go for a 'for ' loop but thanks to my confusing instructor I'm stuck with using an unfamiliar function 's.split' so...
    I'm stuck!

    And wait! It has a continuation!

    Write a function readEntryList that takes a string (a file name), reads that fi le, and interprets
    every line in the fi le as a age entries (by calling readEntry). The function should return a list of
    entries in the same order as in the fi le.
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Rep Power
    Ease up, you'll get it. python's not so hard. I've stuck in a useful debugging statement to help you understand. Object data type is quite important---display it. Also, the documentation is extensive. You can command, to the python interpreter,

    >>> help(list) # for example
    >>> dir(some_object) # to find its methods.
    def readEntry(s): 
        fields = s.split(':')
        print('debug>',type(fields),'fields holds:',fields)
        info = {}  
        info["name"] = fields[0]
        info["age"] = int(fields[1])
        return info
    def readEntryList(filename):
        with open(filename,'r') as input_stream:
            result = [readEntry(line) for line in input_stream]
        return result
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo