Thread: Dictionaries

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

    Join Date
    Oct 2013
    Posts
    5
    Rep Power
    0

    Red face Dictionaries


    Okay so I'm a total beginner to python and my professor is assigning homework that goes way above and beyond what she covers in class. I'm asked to write a function for a problem that 'opens' a .CSV file (containing text abbreviations and their values ('lol' and 'laugh out loud') and organizes all the text information into a dictionary where the key is the text abbreviation and the value is the statement itself. So far I have the file open, but I cant write a for loop that will 'extract' this information. Please advise.

    this is what my code looks like so far

    Code:
    def CreateDictionary():
    	myfile = open("TextToEnglish.csv", "r")
    	mydict = {}
    	for line in myfile:
    		line = line.split()
    	
    		
    CreateDictionary()
    I know I have to do something with .split but I;m seriously at a loss for how to format this code. Please and Thanks again!
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    You're doing well.
    Code:
    # pass the file's name to CreateDictionary.  That way you'll be able to
    # use it on more than one file without editing the function.
    
    # later as an argument we'll pass, instead of a filename,
    # any object with an iterator that returns str data.
    # That moves the file open statement out of the function all together.
    
    def CreateDictionary(filename):
        myfile = open(filename, "r")
        mydict = {}
        for line in myfile:
    
            # Memory abounds.
            # Let's use a new variable.
            # fields is a better name than line.  line already means something.
            fields = line.split(',')  # split your Comma Separated Values at the commas
    
            if len(fields) == 2:  # basic error handling.  Are there 2 values?
    
                (key, value) = fields  # from your example, these are key and value
    
                # advanced version, remove extra white space from key and value
                # you need this.
                (key, value) = map(str.strip, fields)
    
                mydict[key] = value
    
        myfile.close() # close the file.  Later we'll use the with statement in file context
    
        return mydict  # the function gives back result
    
    
    import pprint  # make the output look nice with not much effort.
    pprint.pprint(CreateDictionary('a' or "TextToEnglish.csv"))
    
    
    
    # And I now finally understand context.
    
    # with open("TextToEnglish.csv") as input_stream:
    #     print(CreateDictionary(input_stream))
    
    # translates to English as
    # "Use CreateDictionary in the context of this file stream."
    # And that is beautiful.
    
    # I may be slow but I'm still making headway.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by b49P23TIvg
    You're doing well.
    Code:
    # pass the file's name to CreateDictionary.  That way you'll be able to
    # use it on more than one file without editing the function.
    
    # later as an argument we'll pass, instead of a filename,
    # any object with an iterator that returns str data.
    # That moves the file open statement out of the function all together.
    
    def CreateDictionary(filename):
        myfile = open(filename, "r")
        mydict = {}
        for line in myfile:
    
            # Memory abounds.
            # Let's use a new variable.
            # fields is a better name than line.  line already means something.
            fields = line.split(',')  # split your Comma Separated Values at the commas
    
            if len(fields) == 2:  # basic error handling.  Are there 2 values?
    
                (key, value) = fields  # from your example, these are key and value
    
                # advanced version, remove extra white space from key and value
                # you need this.
                (key, value) = map(str.strip, fields)
    
                mydict[key] = value
    
        myfile.close() # close the file.  Later we'll use the with statement in file context
    
        return mydict  # the function gives back result
    
    
    import pprint  # make the output look nice with not much effort.
    pprint.pprint(CreateDictionary('a' or "TextToEnglish.csv"))
    
    
    
    # And I now finally understand context.
    
    # with open("TextToEnglish.csv") as input_stream:
    #     print(CreateDictionary(input_stream))
    
    # translates to English as
    # "Use CreateDictionary in the context of this file stream."
    # And that is beautiful.
    
    # I may be slow but I'm still making headway.
    I'm going to class right now so i don't have time to study your comment yet! Thank you so much for replying, I'll be back soon!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by b49P23TIvg
    You're doing well.
    Code:
    # pass the file's name to CreateDictionary.  That way you'll be able to
    # use it on more than one file without editing the function.
    
    # later as an argument we'll pass, instead of a filename,
    # any object with an iterator that returns str data.
    # That moves the file open statement out of the function all together.
    
    def CreateDictionary(filename):
        myfile = open(filename, "r")
        mydict = {}
        for line in myfile:
    
            # Memory abounds.
            # Let's use a new variable.
            # fields is a better name than line.  line already means something.
            fields = line.split(',')  # split your Comma Separated Values at the commas
    
            if len(fields) == 2:  # basic error handling.  Are there 2 values?
    
                (key, value) = fields  # from your example, these are key and value
    
                # advanced version, remove extra white space from key and value
                # you need this.
                (key, value) = map(str.strip, fields)
    
                mydict[key] = value
    
        myfile.close() # close the file.  Later we'll use the with statement in file context
    
        return mydict  # the function gives back result
    
    
    import pprint  # make the output look nice with not much effort.
    pprint.pprint(CreateDictionary('a' or "TextToEnglish.csv"))
    
    
    
    # And I now finally understand context.
    
    # with open("TextToEnglish.csv") as input_stream:
    #     print(CreateDictionary(input_stream))
    
    # translates to English as
    # "Use CreateDictionary in the context of this file stream."
    # And that is beautiful.
    
    # I may be slow but I'm still making headway.
    When I execute this code I get this in terminal:

    Code:
    Traceback (most recent call last):
        File "ThePYFile.py", line 16 in <module>
           pprint.pprint(CreateDictionary('a' or "TextToEnglish.csv"))
    TypeError: CreateDictionary() takes no arguments (1 given)
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    It's difficult to write down what you did, even when you know what you did. Had you done what you said, you more likely would have received a message about not finding the file `a' .

    I usually don't post untested code, and when I do I usually include some sort of forewarning message about it being untested.

    I tested the program I posted using python3. In the current directory was a file named `a' . In that text file were two lines with a single comma in them. The program output was the dictionary I expected, not an error message. The only part of my code I see that would operate differently in python2 is the map function output, which in python3 is an iterator instead of a list. Either way, the tuple assignment to (key, value) will result in the same effect at the end of the statement.

    I had intended to remove the `'a' or' part of the expression, but forgot. That won't change your niladic function definition.

    I didn't post a niladic function definition here.
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by b49P23TIvg
    It's difficult to write down what you did, even when you know what you did. Had you done what you said, you more likely would have received a message about not finding the file `a' .

    I usually don't post untested code, and when I do I usually include some sort of forewarning message about it being untested.

    I tested the program I posted using python3. In the current directory was a file named `a' . In that text file were two lines with a single comma in them. The program output was the dictionary I expected, not an error message. The only part of my code I see that would operate differently in python2 is the map function output, which in python3 is an iterator instead of a list. Either way, the tuple assignment to (key, value) will result in the same effect at the end of the statement.

    I had intended to remove the `'a' or' part of the expression, but forgot. That won't change your niladic function definition.

    I didn't post a niladic function definition here.

    I got it working with:
    Code:
    def CreateDictionary(TextToEnglish):
    	myfile = open("TextToEnglish.csv", "r")
    	mydict = {}
    	for line in myfile:
    		fields = line.split(',')  # split Comma Separated Values at the commas
    		if len(fields) == 2:  #Are there 2 values?
    			(key, value) = fields  #these are key and value
    			(key, value) = map(str.strip, fields)
    			mydict[key] = value
    	myfile.close() # close the file
    	return mydict  # the function gives back result
    
      
    import pprint  # make the output look nice 
    pprint.pprint(CreateDictionary("TextToEnglish.csv"))
    But my next step is to create a function 'main' that prompts the user to enter a text abbreviation, and then check if the it matches the 'key', if it does then it prints the value (english words). I'm stumped.

    This is what I have so far

    Code:
    def main():
    	abbreviation_dict = CreateDictionary()
  12. #7
  13. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    key = some_sort_of_prompt('define...')
    if key in dictionary: print(dictionary[key])


    it's not hard.
    [code]Code tags[/code] are essential for python code and Makefiles!
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by b49P23TIvg
    key = some_sort_of_prompt('define...')
    if key in dictionary: print(dictionary[key])


    it's not hard.
    Sorry this must seem very trivial, like I said I'm a beginner . This is what I've built from my initial abomination. It isn't working yet but I'm getting closer....


    Code:
    def CreateDictionary(TextToEnglish):
    	myfile = open("TextToEnglish.csv", "r")
    	mydict = {}
    	for line in myfile:
    		fields = line.split(',')  # split Comma Separated Values at the commas
    		if len(fields) == 2:  #Are there 2 values?
    			(key, value) = fields  #these are key and value
    			(key, value) = map(str.strip, fields)
    			mydict[key] = value
    	myfile.close() # close the file
    	return mydict  # the function gives back result
    
    
    def main():
    	key = input("Please input a text abbreviation")
    	if key in CreateDictionary("TextToEnglish.csv"): 
    		print(CreateDictionary[key])
  16. #9
  17. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    Code:
    def main():
        key = input("Please input a text abbreviation")
        definitions = CreateDictionary("TextToEnglish.csv")
        if key in definitions: 
            print(definitions[key])
    get it???


    Given the rule that programs should fail as soon as possible, that would mean don't trouble the user for input if building the dictionary fails. Therefor I'd switch the lines

    definitions = CreateDictionary("TextToEnglish.csv")
    key = input("Please input a text abbreviation")


    Now, the dictionary could take a long time to construct. Maybe the user won't notice if he's busy thinking about what he wants to look up. So I'd leave the lines of code in the perfect order we find here, asking the question first.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo