Hard time with dictionnary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pmstel
    New Member
    • Aug 2007
    • 9

    Hard time with dictionnary

    I have a dictionnary with variable in it that I would like to get it in global variable.


    example:

    Code:
    sketch_dict = { "width":48.0, "length":12.5, "thk":0.75 }
    for it in sketch_dict:
        if string.split( it, "__" )[0] == "":
            pass
        else:
            global it
            print it," = ",sketch_dict[ it ]
            it = sketch_dict[ it ]
    I was expecting from that to be able to call width*length*th k but I get glabal name error.

    If I do:

    Code:
    print width
    I get the same error. But if I do this:

    Code:
    print it
    I just get whatever the last item have been use by my loop and not the other one. I know I can do this:

    Code:
    print sketch_dict['width'] * sketch_dict['length'] * sketch_dict['thk']
    But when the dictionnary have over 375 item in it, it is not funny. Any idea how I could turn it into local variable or global variable?
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    What you are trying to do is very wrong. By saying global it you are simply making "it" referable from a global scope; not what "it" points to. Why don't you just have a variable outside the loop to store the entries that you want.

    And what do you mean it is not funny? If you have 375 items in a dictionary why wouldn't you call them by name? I don't understand what your dilemma is here...

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Quick and dirty:[code=Python]globals().updat e(sketch_dict)[/code]

      Comment

      • pmstel
        New Member
        • Aug 2007
        • 9

        #4
        Originally posted by bvdet
        Quick and dirty:[code=Python]globals().updat e(sketch_dict)[/code]
        I have tried that before you submit the solution but for some reason that I cannot understand, some variable are not updated. When I run this piece of code to see if it's getting read by another function that I have written, I can print the variable name and his value.

        Code:
         
        for it in sketch_dict:
        	if it == "poker_game":
        		print "\n\nFound variable " + it + " and it is equal to " + sketch_dict[ it ] + "\n\n"
         
        globals().update( sketch_dict )
        With that code before the globals().updat e, I can validate if the famous variable is there and I just print it to the screen. But like I said some of them are not found when I try to use it after the globals().updat e. I get == > UnboundLocalErr or: local variable 'poker_game' referenced before assignment

        If i don't use globals().updat e, then nothing works at all. The first variable I call to do something return me the same error mention above. If I globals().updat e it, much better. If I do it manually like this:

        Code:
        global poker_game, blackjack_game, player1, player2 ...
        poker_game = poker_game
        blackjack_game = blackjack_game
        player1 = player1
        player2 = player2
        ...
        It is fine all the way but I have close to 400 variable like I said. Doing global to 400 variable the asigning it to itself 400 time, it is a lot of space or line of code consuming.
        Last edited by pmstel; May 15 '08, 10:35 AM. Reason: missing description of problem

        Comment

        • pmstel
          New Member
          • Aug 2007
          • 9

          #5
          Originally posted by pmstel
          Code:
          global poker_game, blackjack_game, player1, player2 ...
          poker_game = poker_game
          blackjack_game = blackjack_game
          player1 = player1
          player2 = player2
          ...
          Either if I just do it like mention above, I have just find out the I must previously do the globals().updat e( sketch_dict ) before doing all the global stuff. Otherwise it still do not work.

          Any shortcut to simplify this will be appreciated. Thanks!

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            It's a lot simpler than you are making it. There is no need to use the global statement. Example:
            [code=Python]>>> dd3 = {'s1':12, 's2':15, 's3':22.5, 'aList':[1,2,3], 'aBadList1':'[a,b,c]', 'aBadList2': '[1,2,3'}
            >>> s1
            Traceback (most recent call last):
            File "<interacti ve input>", line 1, in ?
            NameError: name 's1' is not defined
            >>> globals().updat e(dd3)
            >>> s1
            12
            >>> [/code]The global namespace for a function is always the module in which the function was defined. If a module's global namespace is updated, the variables will only be available in that namespace.

            Comment

            • pmstel
              New Member
              • Aug 2007
              • 9

              #7
              bvdet,

              I tried out what you have post and fully understand of what is going on and it makes sense. We use the same detailing software. If I do not use globals().updat e( my_dictionnary ), it won't work at all. I need to do it manually ===> var_name = dd['var_name']. I would like to avoid doing this. If I use globals().updat e( my_dictionnary) , then it works partially.



              1. I read a text file that actually read each line and create a dictionnary to be able to use variable in a dialog box.

              2. I was wondering if there is a limitation for the number of item in a dictionnary because the same piece of code work fine in another script. That script was having a text file were maybe 200 or 250 items was there. Now with 400 items, it does not work properly. Strange!!!

              3. If do this:
              Code:
              globals().update( my_dictionnary )
              global var1_problem_on_it
              var1_problem_on_it = var1_problem_on_it
              that wil actually keep my script running fine until the end or the next error.

              I'm confuse.

              Sample of my importing script. You might recongnize it bvdet:

              Code:
              def read_data_from_sketch(file, filename, filenumb):
              	try:
              		ff = open(file)
              	except:
              		print ""
              		print "You asked for this sketch number ===> ",filenumb
              		print "I am looking for this file name ===> ",filename
              		print "And I can't find this file name in his folder. If you have type the proper sketch"
              		print "number, verify with the person in charge if that file actually exist in the"
              		print "appropriate folder."
              		print ""
              		return 0
              	else:
              		dd = {}
              		key_values_list = ff.readlines()[3:]
              		ff.close()
              		for ii in key_values_list:
              			key_name, key_value = ii.split(",", 1)
              			try:
              				dd[key_name.strip()] = inumbfloat(key_value.strip())
              			except:
              				dd[key_name.strip()] = key_value.strip()
              		return dd
              adn here is what I do when I want to read and import my text file inside my script.

              Code:
              sketch_dict = read_data_from_sketch(sketch_file_import, sketch_file_name, sketch)
              globals().update( sketch_dict )
              In read_data_from_ sketch, the argument file is actually the full path plus the filename. The other arguement is only there for troubleshooting info at screen.

              Thoses pieces of code are working fine. I'm using it all the time to read file that I create manually or file that are saved by other script. Now for this one, error over error until I do :

              Code:
              globals().update( my_dictionnary )
              global var1_problem_on_it
              var1_problem_on_it = var1_problem_on_it
              I'm lost

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                pmstel,

                You are doing something similar to me. I have not had your problem however. I suspect there may be another problem that is not apparent but has an effect on importing your variable data. Send your offending data file to me by email, and I will attempt to import it. You can get my email address from the Users List on SDS/2.com.

                Comment

                • woooee
                  New Member
                  • Mar 2008
                  • 43

                  #9
                  Perhaps I am missing the point, but why not just use a class. Also, note that you can use if "something" in self.sketch_dic , instead of comparing every key.
                  Code:
                  class test_class:
                      def __init__(self):
                         self.sketch_dic = {}
                         self.test_data()
                  
                      def find_in_dic(self, words_to_find):
                         if words_to_find in self.sketch_dic:
                            print "\nFound variable ", words_to_find, \
                                  "and it is equal to -->", self.sketch_dic[words_to_find ] + "\n"
                         else:
                            print words_to_find, "NOT found"
                  
                      def test_data(self):
                         test_tuple = ("poker_game", "blackjack_game", "player1", "player2")
                         for words in test_tuple:
                            self.sketch_dic[words] = "test of " + words
                  
                  
                  TC=test_class()
                  print TC.sketch_dic
                  TC.find_in_dic("blackjack_game")
                  TC.find_in_dic("player1")
                  TC.find_in_dic("test_fail")

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    pmstel sent the data file to me and I was able to import all the data if I iterated on the file object, but only part of the data if I iterated on the list produced by file_object.rea dlines(). The file is in CSV format saved from Excel, and the lines terminat with '\r\n'. I also tried file_object.rea d().split('\r\n ') with the same partial results.

                    Data file sample:
                    Code:
                    sketch_vb,VB105
                    sketch_made_by,Client
                    hinge_line_check,0
                    check_load,0
                    tc_bolt,No
                    design_method,CSA
                    design_method_factor,2
                    ___Validation_Section_Size_Begin,__
                    col_section_size,W1000x371
                    beam_section_size,W530x85
                    Following are the three methods used to read the file into a list:[code=Python]
                    # partial results
                    data = [item.strip().sp lit(',',1) for item in f.read().split( '\r\n') if not item.startswith ('_')]
                    # partial results
                    data = [item.strip().sp lit(',',1) for item in f.readlines() if not item.startswith ('_')]
                    # correct results
                    data = [item.strip().sp lit(',',1) for item in f if not item.startswith ('_')]
                    [/code]Can anyone explain this behavior?

                    Comment

                    • woooee
                      New Member
                      • Mar 2008
                      • 43

                      #11
                      Read the file in binary mode and check for anything that might be an EOF, probably a decimal 25 or 26, but could be others (3,4,23??). An EOF is system-specific, so Python may be setting it differently depending on which way it is read. Try this question on http://groups.google.com/group/comp.lang.python/ There should be someone there who would know more.

                      Comment

                      • bvdet
                        Recognized Expert Specialist
                        • Oct 2006
                        • 2851

                        #12
                        Originally posted by woooee
                        Read the file in binary mode and check for anything that might be an EOF, probably a decimal 25 or 26, but could be others (3,4,23??). An EOF is system-specific, so Python may be setting it differently depending on which way it is read. Try this question on http://groups.google.com/group/comp.lang.python/ There should be someone there who would know more.
                        Thanks for the info woooee. I tried reading the file 'r', 'rb', and 'rU' with the same results.

                        Comment

                        Working...