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

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3

    Python - Dictionary Issue


    Hi,

    I condensed and posted the necessary parts of my codes to show the problem. I am trying to get the program to store information in a dictionary and later print it example as:

    module1 : marks
    module2: marks

    and so on. I am able to store the information into a dictionary But unable to print it out as above. The codes below consists two of the methods I been working on.

    The 1st one I pretty much understand why it is not working(Just kept it in, in case I am wrong and actually that is closely correct). The 2nd one stores the information fine and am confused as to why it is not printing it out right.

    Please advice, thanks.

    P.S: I checked and double checked and the codes are properly indented when I tried. Sorry if they are out of alignment again.. Something wrong with my posting I believe..

    Code:
    students = []
    
    class Student:
        grades = {}
        new_Dict = {}
        
    # 1st try
        def setGrades(self, grades):
            self.grades = grades
        def getGrades(self):
            return self.grades
    # 2nd try
        def setnew_Dict(self, new_Dict):
            self.new_Dict = new_Dict
        def getnew_Dict(self):
            return self.new_Dict
    
    def addStudent():
        new_Dict = {}
        F6 = '0'
        F7 = '-2'
        while F6 != 'done':
            F6 = raw_input("Please enter module name. type 'done' to quit: ")
            if F6 == 'done':
                break
            F7 = raw_input("Please enter the grades for %s: " % F6)
            new_Dict[F6] = F7 # 2nd try - This works and adds the data to the dictionary 
    
        student = Student() 
        student.setGrades({F6:F7})# 1st try
        student.setnew_Dict({F6:F7}) # 2nd try
        students.append(student)
        
        print new_Dict # Printing this just to show that the information gets stored in the dictionary
    
    def printStudents():
        for person in students:
            print 'Grades: ' + str(person.getGrades()) #1st try
            print '----------------------------------------'
            print "new_Dict: " + str(person.getnew_Dict()) # 2nd try
    
    userInput = 0
    while userInput != '-1':
        print '1. Add a student (to the database)'
        print '2. Print all students (in the database)'
        
        userInput = raw_input('What would you like to do <type a number or -1 to quit. ')
        if userInput == '1':
            addStudent()
        elif userInput == '2':
            printStudents()
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    I don't really follow what your 2 attempts are really getting at. Maybe you're just trying to print the dictionary but to get the data formatted you should use something like:
    for mod in dctName: print '{0}: {1}'.format(mod,dctName[mod])
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3
    Hi,

    when you run the program and for example enter science for the module and 10 for the grades. You let the loop run and again enter history for the module and 20 for the grades.

    The print out for the above should be:

    science: 10
    history: 20

    But what I am getting on both attempts is:

    {done:20}

    It overwrites my previous inputs thus not storing all the information. I am using 'done' to break the loop and this word 'done' ends up in the print.

    Thanks for input.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    Sorry keshk. Your program displays a lot of misunderstanding. I can't tell what you want so I'll just address the one question.

    To insert an item into a dictionary use
    dictionary[key] = value

    To insert many items from another dictionary use
    dictionary.update(another_dictionary)

    Your code replaces the entire dictionary. I'll mark what happens when you enter `done'.
    Code:
    def addStudent():
        new_Dict = {}
        F6 = '0'
        F7 = '-2'
        while F6 != 'done':
            F6 = raw_input("Please enter module name. type 'done' to quit: ")
            if F6 == 'done':
                break        ############ F6 stores 'done'  #########  F7 is -2 or the last thing you entered
            F7 = raw_input("Please enter the grades for %s: " % F6)
            new_Dict[F6] = F7 # 2nd try - This works and adds the data to the dictionary 
    
        student = Student() 
        student.setGrades({F6:F7})# 1st try  ########## you make a dictionary of {'done': (object of F7)}  ########
    
    
    
        def setGrades(self, grades):
            self.grades = grades   ####### replaces self.grades with {'done': (object of F7)}  #########

    PS. How do I know this? I've spent a lot of time reading the manuals, the tutorial, books about python, and I've practiced python since last millennium.
    Last edited by b49P23TIvg; December 11th, 2012 at 03:06 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3
    Hm, clearly bad presentation by me. 2 out of 2 doesn't get me.


    I initially created a class and created a dictionary under it. I am using this dictionary to store module names and grades for the modules.

    Right now, I am able to store the information in the dictionary. I was using the advice you mentioned - new_Dict[F6] = F7

    I do get the idea of why 'done' gets added and why the dictionary keeps getting replaced as you explained. I removed the 2 tries and just keeping to one now.

    To test it, I printed out the dictionary (within the addStudent function) and I get the result as:

    {'module1':'10', 'module2':'20', 'module3':'30' }

    This shows that 'done' no longer gets into the dictionary and that it adds the inputs instead of replacing a previous entry.

    But when I do the same print in my printStudent function, it prints out as {done: 10} going back to the same situation.

    Hope am clearer now. Trying to get thoughts in place. Thanks.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3
    Having one more small issue. I am trying to format the print out to look as follows:

    a: john
    b: kelly

    so I typed the following codes:

    Code:
    for x in str(person.getGrades()):
                print "%s:%s" % x
    It returns an error message saying not enough arguments for format string. Any idea what I'm doing wrong?

    It prints out when I just print x without any formatting. So I believe the issue is in the way I have structured the format. Do advice. Sorry if its confusing when I show only parts of the entire code. Will post the entire work if needed to clarify. Thanks.
  12. #7
  13. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    When you treat a dictionary as an iterator, all you get back is the keys. The dictionary method, <dictionary name>.items(), returns key-value pairs.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3
    Hi,

    I am getting both the key and value via my printing. Just not getting the format of the print right.

    If I do the following without any formatting, I get both key and value. Error only occurs when I use formatting i.e '%s:%s' %

    Code:
    for x in str(person.getGrades()):
                print x
    But the output comes out as:

    Code:
    {
    '
    a
    '
    :
    '
    john
    '
    }
    Bad print format but nevertheless holds the key and value. Thus am asking how to format the print as follows:

    Code:
    a:John

    Thanks.
  16. #9
  17. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    import pprint
    string = pprint.pformat(my_object)
    # additional string processing (usually unnecessary)
    print(string)
    [code]Code tags[/code] are essential for python code and Makefiles!
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3
    Hi,

    Just to recap, I am looking to print out as follows"

    a:1
    b:2
    c:3

    I used your guide; and input the following codes:

    Code:
    import pprint
    
    string = pprint.pformat(str(person.getGrades()))
    print (string)
    It still returns the print out as:

    Code:
    {'a': '1', 'c': '3', 'b': '2'}
    Also tried the following codes and it returns the same method of print out:

    Code:
    import pprint
    
    pprint.pprint ("Grades: " + str(person.getGrades()))
    Do advice. Tnks.
  20. #11
  21. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    d=dict(a=1,b=2,c=3)
    for item in d.items():
    print('%s:%s'%item)
    [code]Code tags[/code] are essential for python code and Makefiles!
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    3
    Hi,

    I amended the codes to read as follows and it works:


    Code:
    print "Grades: "        
            a = (person.getGrades())
            for x in a.items():
                print ('         %s:%s'% x)
    the items() function is what that is keep the error from occurring. From my understanding, it is used to return a list of dictionary keys and values. Tried with .iteritems and it works too. Thanks so much for guidance.

IMN logo majestic logo threadwatch logo seochat tools logo