944,111 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 511
  • Python RSS
Nov 8th, 2009
0

Problems with dictionaries

Expand Post »
Assume I have a file of the following format:
a,1
b,2
c,3
d,4
Here is my code:
Python Syntax (Toggle Plain Text)
  1. def junk(f):
  2. d1 = {}
  3. d2 = {}
  4. for line in f:
  5. columns = line.split(":")
  6. letters = columns[1]
  7. numbers = columns[2]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return (d1, d2)
  11.  
  12.  
  13. def something():
  14. print d1
  15. print d2
  16.  
  17. if __name__ == "__main__":
  18. f = open("filename.txt")
  19. d1 = junk(f)[0]
  20. d2 = junk(f)[1]

Assume I want to call function something. It cannot print d1 and d2 unless I add them to the main block. As soon as I add d1 and d2 to the "main" block and call either of the two functions, both return two empty dictionaries. Why does this happen? How can I fix it? Please help!
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
pyprog is offline Offline
31 posts
since Oct 2009
Nov 8th, 2009
0
Re: Problems with dictionaries
First you are not returning a dictionary. I've added a print statement to show that. Also, take a look at "returns" and "arguments" here http://www.penzilla.net/tutorials/python/functions/ for the "something" function.
Python Syntax (Toggle Plain Text)
  1. def junk(f):
  2. d1 = {}
  3. d2 = {}
  4. for line in f:
  5. columns = line.split(":")
  6. letters = columns[1]
  7. numbers = columns[2]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return (d1, d2)
  11.  
  12.  
  13. def something():
  14. print d1
  15. print d2
  16.  
  17. if __name__ == "__main__":
  18. f = open("filename.txt")
  19. d1 = junk(f)[0]
  20. print "type d1 =", type(d1)
  21. d2 = junk(f)[1]
Last edited by woooee; Nov 8th, 2009 at 1:19 pm.
Reputation Points: 741
Solved Threads: 693
Nearly a Posting Maven
woooee is offline Offline
2,307 posts
since Dec 2006
Nov 8th, 2009
0
Re: Problems with dictionaries
Click to Expand / Collapse  Quote originally posted by woooee ...
First you are not returning a dictionary. I've added a print statement to show that. Also, take a look at "returns" and "arguments" here http://www.penzilla.net/tutorials/python/functions/ for the "something" function.
Python Syntax (Toggle Plain Text)
  1. def junk(f):
  2. d1 = {}
  3. d2 = {}
  4. for line in f:
  5. columns = line.split(":")
  6. letters = columns[1]
  7. numbers = columns[2]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return (d1, d2)
  11.  
  12.  
  13. def something():
  14. print d1
  15. print d2
  16.  
  17. if __name__ == "__main__":
  18. f = open("filename.txt")
  19. d1 = junk(f)[0]
  20. print "type d1 =", type(d1)
  21. d2 = junk(f)[1]
I still don't get it. The type of d1 is dictionary.
Reputation Points: 10
Solved Threads: 0
Light Poster
pyprog is offline Offline
31 posts
since Oct 2009
Nov 8th, 2009
0
Re: Problems with dictionaries
Try this and then go to the page from the earlier link which explains why you returned a tuple.
Python Syntax (Toggle Plain Text)
  1. def junk(f):
  2. d1 = {}
  3. d2 = {}
  4. for line in f:
  5. columns = line.split(":")
  6. letters = columns[1]
  7. numbers = columns[2]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return d1, d2
  11.  
  12. if __name__ == "__main__":
  13. f = open("filename.txt")
  14. d1_ret, d2_ret = junk(f)[0]
  15. print type(d1_ret)
Reputation Points: 741
Solved Threads: 693
Nearly a Posting Maven
woooee is offline Offline
2,307 posts
since Dec 2006
Nov 8th, 2009
0
Re: Problems with dictionaries
Click to Expand / Collapse  Quote originally posted by woooee ...
Try this and then go to the page from the earlier link which explains why you returned a tuple.
Python Syntax (Toggle Plain Text)
  1. def junk(f):
  2. d1 = {}
  3. d2 = {}
  4. for line in f:
  5. columns = line.split(":")
  6. letters = columns[1]
  7. numbers = columns[2]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return d1, d2
  11.  
  12. if __name__ == "__main__":
  13. f = open("filename.txt")
  14. d1_ret, d2_ret = junk(f)[0]
  15. print type(d1_ret)
OK, I see that putting a comma between two variables automatically returns a tuple. But the problem is that as long as d1(d1_ret) or d2(d2_ret) in the "main" block junk(f) would return twoempty dictionaries in a tuple. That is what I don't understand.
Reputation Points: 10
Solved Threads: 0
Light Poster
pyprog is offline Offline
31 posts
since Oct 2009
Nov 8th, 2009
0
Re: Problems with dictionaries
Click to Expand / Collapse  Quote originally posted by pyprog ...
Assume I have a file of the following format:
a,1
b,2
c,3
d,4
Here is my code:
Python Syntax (Toggle Plain Text)
  1. def junk(f):
  2. d1 = {}
  3. d2 = {}
  4. for line in f:
  5. columns = line.split(":")
  6. letters = columns[1]
  7. numbers = columns[2]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return (d1, d2)
  11.  
  12.  
  13. def something():
  14. print d1
  15. print d2
  16.  
  17. if __name__ == "__main__":
  18. f = open("filename.txt")
  19. d1 = junk(f)[0]
  20. d2 = junk(f)[1]

Assume I want to call function something. It cannot print d1 and d2 unless I add them to the main block. As soon as I add d1 and d2 to the "main" block and call either of the two functions, both return two empty dictionaries. Why does this happen? How can I fix it? Please help!
Really just a series of somewhat careless beginner mistakes you can fix this way ...
python Syntax (Toggle Plain Text)
  1. """assume file "filename.txt" has this content
  2. a,1
  3. b,2
  4. c,3
  5. d,4
  6. """
  7.  
  8. def junk(f):
  9. d1 = {}
  10. d2 = {}
  11. for line in f:
  12. columns = line.split(",") # <---- delimiter is comma
  13. letters = columns[0] # <---- index starts with 0
  14. numbers = columns[1] # <---- index again
  15. d1[letters] = numbers
  16. d2[numbers] = letters
  17. return d1, d2
  18.  
  19. def something(d1, d2): # <---- give function proper arguments
  20. print d1
  21. print d2
  22.  
  23. if __name__ == "__main__":
  24. f = open("filename.txt")
  25. d1, d2 = junk(f) # expand the tuple that is returned
  26. something(d1, d2) # give function its needed arguments
  27.  
  28. """my output -->
  29. {'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
  30. {'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
  31. """
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 8th, 2009
0
Re: Problems with dictionaries
Click to Expand / Collapse  Quote originally posted by vegaseat ...
Really just a series of somewhat careless beginner mistakes you can fix this way ...
python Syntax (Toggle Plain Text)
  1. """assume file "filename.txt" has this content
  2. a,1
  3. b,2
  4. c,3
  5. d,4
  6. """
  7.  
  8. def junk(f):
  9. d1 = {}
  10. d2 = {}
  11. for line in f:
  12. columns = line.split(",") # <---- delimiter is comma
  13. letters = columns[0] # <---- index starts with 0
  14. numbers = columns[1] # <---- index again
  15. d1[letters] = numbers
  16. d2[numbers] = letters
  17. return d1, d2
  18.  
  19. def something(d1, d2): # <---- give function proper arguments
  20. print d1
  21. print d2
  22.  
  23. if __name__ == "__main__":
  24. f = open("filename.txt")
  25. d1, d2 = junk(f) # expand the tuple that is returned
  26. something(d1, d2) # give function its needed arguments
  27.  
  28. """my output -->
  29. {'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
  30. {'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
  31. """
But how come if you call the function junk again after the program finished executing and showed the output, it will return two empty dicts?
Last edited by pyprog; Nov 8th, 2009 at 3:28 pm.
Reputation Points: 10
Solved Threads: 0
Light Poster
pyprog is offline Offline
31 posts
since Oct 2009
Nov 8th, 2009
0
Re: Problems with dictionaries
Click to Expand / Collapse  Quote originally posted by pyprog ...
But how come if you call the function junk again after the program finished executing and showed the output, it will return two empty dicts?
Because the code is also poorly designed, ideally you should send the file name to the function, open the file there, read and close it.

You can fix your code this way ...
python Syntax (Toggle Plain Text)
  1. def junk(fh):
  2. d1 = {}
  3. d2 = {}
  4. for line in fh:
  5. columns = line.split(",")
  6. letters = columns[0]
  7. numbers = columns[1]
  8. d1[letters] = numbers
  9. d2[numbers] = letters
  10. return d1, d2
  11.  
  12. def something(d1, d2):
  13. print d1
  14. print d2
  15.  
  16. if __name__ == "__main__":
  17. fh = open("filename.txt")
  18. d1, d2 = junk(fh)
  19. something(d1, d2)
  20. print( '-'*50 )
  21. # second time around
  22. # file handle fh is at the end of the file now
  23. # reset it to the start of the file
  24. fh.seek(0)
  25. d1, d2 = junk(fh)
  26. something(d1, d2)
  27.  
  28. """my output -->
  29. {'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
  30. {'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
  31. --------------------------------------------------
  32. {'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
  33. {'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
  34. """
This would have been the better design ...
python Syntax (Toggle Plain Text)
  1. """assume file "filename.txt" has this content
  2. a,1
  3. b,2
  4. c,3
  5. d,4
  6. """
  7.  
  8. def file2dictionary(fname):
  9. """
  10. read data from file and create a dictionary d1 and its reverse d2
  11. """
  12. fh = open("filename.txt")
  13. d1 = {}
  14. d2 = {}
  15. for line in fh:
  16. columns = line.split(",")
  17. letters = columns[0]
  18. numbers = columns[1]
  19. d1[letters] = numbers
  20. d2[numbers] = letters
  21. fh.close()
  22. return d1, d2
  23.  
  24. def print_dict(d1, d2):
  25. """print the two dictionaries d1 and d2"""
  26. print(d1)
  27. print(d2)
  28.  
  29. if __name__ == "__main__":
  30. fname = "filename.txt"
  31. d1, d2 = file2dictionary(fname)
  32. print_dict(d1, d2)
  33. print( '-'*50 )
  34. # test second time around
  35. d1, d2 = file2dictionary(fname)
  36. print_dict(d1, d2)
  37.  
  38. """my output -->
  39. {'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
  40. {'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
  41. --------------------------------------------------
  42. {'a': '1\n', 'c': '3\n', 'b': '2\n', 'd': '4'}
  43. {'3\n': 'c', '1\n': 'a', '4': 'd', '2\n': 'b'}
  44. """
Note:
If you use the print() function instead of the print statement this code will work with Python2 and Python3.
Last edited by vegaseat; Nov 8th, 2009 at 4:02 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Pythagoras?
Next Thread in Python Forum Timeline: Validate Raw Input





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC