Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old December 11th, 2012, 01:08 PM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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()

Reply With Quote
  #2  
Old December 11th, 2012, 01:40 PM
rrashkin's Avatar
rrashkin rrashkin is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2012
Location: 39N 104.28W
Posts: 90 rrashkin User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 13 h 39 m 14 sec
Reputation Power: 2
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])

Reply With Quote
  #3  
Old December 11th, 2012, 01:47 PM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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.

Reply With Quote
  #4  
Old December 11th, 2012, 02:03 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,357 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 10 m 17 sec
Reputation Power: 383
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.
__________________
[code]Code tags[/code] are essential for python code!

Last edited by b49P23TIvg : December 11th, 2012 at 02:06 PM.

Reply With Quote
  #5  
Old December 11th, 2012, 03:19 PM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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.

Reply With Quote
  #6  
Old December 12th, 2012, 11:16 AM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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.

Reply With Quote
  #7  
Old December 12th, 2012, 11:25 AM
rrashkin's Avatar
rrashkin rrashkin is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2012
Location: 39N 104.28W
Posts: 90 rrashkin User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 13 h 39 m 14 sec
Reputation Power: 2
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.

Reply With Quote
  #8  
Old December 12th, 2012, 12:31 PM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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.

Reply With Quote
  #9  
Old December 12th, 2012, 01:29 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,357 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 10 m 17 sec
Reputation Power: 383
import pprint
string = pprint.pformat(my_object)
# additional string processing (usually unnecessary)
print(string)

Reply With Quote
  #10  
Old December 12th, 2012, 04:10 PM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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.

Reply With Quote
  #11  
Old December 12th, 2012, 04:54 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,357 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 10 m 17 sec
Reputation Power: 383
d=dict(a=1,b=2,c=3)
for item in d.items():
print('%s:%s'%item)

Reply With Quote
  #12  
Old December 12th, 2012, 05:37 PM
keshk keshk is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 36 keshk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 14 h 34 m 48 sec
Reputation Power: 1
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.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Python - Dictionary Issue

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap