simple question using dictionary...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hidrkannan
    New Member
    • Feb 2007
    • 32

    simple question using dictionary...

    [CODE=python]
    aDict = {}
    aDict['a'] = 5
    aDict['bc'] = 'st'
    aDict['zip'] = 12345



    def outputMethod(** aDict):
    print aDict['a']
    print aDict['bc']
    print aDict['zip']
    return
    def outputMethod1(* *aDict):
    for key in aDict:
    ...
    ...
    print a
    print bc
    print zip
    return


    outputMethod(** aDict)
    outputMethod1(* *aDict)
    [/CODE]

    with reference to the above code, I would like to define variables on the fly in outputMethod1 using the dictionary keys as variable names, so that i can print using just the variable names instead using the Dictionary keys as shown in ouputmethod. I am trying a for loop to extract the keys from the dictionary...bu t not sure how to define the "keys" as variable names?

    Thanks in advance.

    SKN
  • woooee
    New Member
    • Mar 2008
    • 43

    #2
    You can store a variable in a dictionary
    a=5
    test_dict["a"]=a
    print test_dict["a"] prints 5
    You can instead store the data in the dictionary since test_dict["a"] points to a points to 5, it is just as easy to store the value 5 as test_dict["a"]

    You can also do test_dict[a]=3 and print a, test_dict[a] would print 5 3
    or b = test_dict["a"], print b would print 5

    Python uses pointers so you can pretty much store any Python object.

    Comment

    • hidrkannan
      New Member
      • Feb 2007
      • 32

      #3
      Originally posted by woooee
      You can store a variable in a dictionary
      a=5
      test_dict["a"]=a
      print test_dict["a"] prints 5
      You can instead store the data in the dictionary since test_dict["a"] points to a points to 5, it is just as easy to store the value 5 as test_dict["a"]

      You can also do test_dict[a]=3 and print a, test_dict[a] would print 5 3
      or b = test_dict["a"], print b would print 5

      Python uses pointers so you can pretty much store any Python object.

      Actually I would like to define variable names using the dictionary keys..to assign the corresponding dictionary values...

      SKN

      Comment

      • Elias Alhanatis
        New Member
        • Aug 2007
        • 56

        #4
        Hello!

        I am a newbee too , so here is a simple solution i suggest:

        Code:
        aDict={'w':1,'e':2,'r':3}
        index=0
        for key in aDict.keys():
            exec(str(aDict.keys()[index])+'='+str(aDict[key]))
            index+=1
        Hope i helped.....

        Comment

        • Elias Alhanatis
          New Member
          • Aug 2007
          • 56

          #5
          Rushed to post the reply but forgot the case of values being strings!!!!!
          Here is the improved ( yet still simple or 'naive' ) suggestion:

          Code:
          a={'w':1,'e':'rt6','r':3}
          index=0
          for key in a.keys():
              if type(a[key])!=type(""):
                  exec(str(a.keys()[index])+'='+str(a[key]))
              else:
                  exec(str(a.keys()[index])+'="'+str(a[key])+'"')
              index+=1
          That will do the job!!!

          Elias

          Comment

          • hidrkannan
            New Member
            • Feb 2007
            • 32

            #6
            Originally posted by Elias Alhanatis
            Rushed to post the reply but forgot the case of values being strings!!!!!
            Here is the improved ( yet still simple or 'naive' ) suggestion:

            Code:
            a={'w':1,'e':'rt6','r':3}
            index=0
            for key in a.keys():
                if type(a[key])!=type(""):
                    exec(str(a.keys()[index])+'='+str(a[key]))
                else:
                    exec(str(a.keys()[index])+'="'+str(a[key])+'"')
                index+=1
            That will do the job!!!

            Elias
            Thanks Elias. But I don't understand the use of index in the above code and also the if construct. how to retain the type of the value..say if the value of one of the keys of type list...

            [CODE=python]
            aDict = {}
            aDict['abc'] = 1
            aDict['defi'] = [2,4]
            aDict['a'] = 5
            aDict['bc'] = 'st'
            aDict['zip'] = 12345
            for kw in aDict:
            #exec(str(a.key s()[index])+'='+str(a[key]))
            exec(str(kw)+'= "'+str(aDic t[kw])+'"')

            print a, bc,zip,abc, defi
            [/CODE]

            Please comment.

            SKN
            Last edited by hidrkannan; Jun 12 '08, 12:26 PM. Reason: Not seem to work

            Comment

            • Elias Alhanatis
              New Member
              • Aug 2007
              • 56

              #7
              Hi again!

              The exec() function takes a string as an argument and just "makes it happen" ,
              so all we must do is create a string that would give us the result we need if we
              typed it in the interactive prompt.
              The trick is that if a value in the dict IS a string , we must 'work our way around' in order not to confuse it with the exec() string we want to produce.
              In any other case ( i suppose ) , there is no problem. ( you can confirm this by changing a value in my code to a list , examp: "w":[3,4,5] ).
              In any case , to make your code error-proof , i sugest that you check the type of each value using the type() function. This is what i've done in my code ( line 4 ).

              The index is used in order to iterate over the keys one by one , since we dont know ahead of time the number of keys in the dict , so we use it as a 'pointer' for each key.

              Try to experiment with the code , google each word or function you don't understand and soon you'll get the idea.....
              ( Thats what i do.....)

              I hope i helped a little!

              Elias

              Comment

              • hidrkannan
                New Member
                • Feb 2007
                • 32

                #8
                Originally posted by Elias Alhanatis
                Hi again!

                The exec() function takes a string as an argument and just "makes it happen" ,
                so all we must do is create a string that would give us the result we need if we
                typed it in the interactive prompt.
                The trick is that if a value in the dict IS a string , we must 'work our way around' in order not to confuse it with the exec() string we want to produce.
                In any other case ( i suppose ) , there is no problem. ( you can confirm this by changing a value in my code to a list , examp: "w":[3,4,5] ).
                In any case , to make your code error-proof , i sugest that you check the type of each value using the type() function. This is what i've done in my code ( line 4 ).

                The index is used in order to iterate over the keys one by one , since we dont know ahead of time the number of keys in the dict , so we use it as a 'pointer' for each key.

                Try to experiment with the code , google each word or function you don't understand and soon you'll get the idea.....
                ( Thats what i do.....)

                I hope i helped a little!

                Elias

                Thanks for your help. Still I am not convinced to use index for the above purpose. Basically I look for an "undict" function (as "dict" function puts all name=value pairs to a dictionary object) to divide the dict object to individual name=value pairs.
                Somehow I feel that if else construct will reduce the performance.

                Thanks again for the "exec" idea that I learnt today.

                SKN

                Comment

                • Elias Alhanatis
                  New Member
                  • Aug 2007
                  • 56

                  #9
                  Inspired by the challenge , i will try to wrap it up in a
                  function without an 'if' clause and without an index. I will do it tonight , cause
                  right now i am at work ( LOL ) , so check this thread out later....

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    I routinely import a dict object upon initializing a script and create the variables to avoid referencing the dictionary every time a value is required. This is the code:
                    [code=Python]for key, value in dd.items():
                    exec "%s = %s" % (key, repr(value)) in None[/code]You may not need the 'in None' in your application. In my applications, the values are limited to int, float, list, and string, and they are created correctly.

                    Comment

                    • hidrkannan
                      New Member
                      • Feb 2007
                      • 32

                      #11
                      Originally posted by bvdet
                      I routinely import a dict object upon initializing a script and create the variables to avoid referencing the dictionary every time a value is required. This is the code:
                      [code=Python]for key, value in dd.items():
                      exec "%s = %s" % (key, repr(value)) in None[/code]You may not need the 'in None' in your application. In my applications, the values are limited to int, float, list, and string, and they are created correctly.

                      Thanks BV. Is it possible to have this as a general function and use it sort of an "undict" opposite of "dict" function...not sure how to return the equivalent "name = Value" pair statements to the calling method. Essentially I am looking for:

                      def aMethod(self,** aDict):
                      undict(aDict)
                      .....
                      .....

                      SKN

                      Comment

                      • hidrkannan
                        New Member
                        • Feb 2007
                        • 32

                        #12
                        Originally posted by hidrkannan
                        Thanks BV. Is it possible to have this as a general function and use it sort of an "undict" opposite of "dict" function...not sure how to return the equivalent "name = Value" pair statements to the calling method. Essentially I am looking for:

                        def aMethod(self,** aDict):
                        undict(aDict)
                        .....
                        .....

                        SKN
                        BV,

                        Also what is the purpose of "in None"...It gave me setitem attribute error..but when I remove "in None", it worked !!

                        Thanks

                        SKN

                        Comment

                        • bvdet
                          Recognized Expert Specialist
                          • Oct 2006
                          • 2851

                          #13
                          Originally posted by hidrkannan
                          Thanks BV. Is it possible to have this as a general function and use it sort of an "undict" opposite of "dict" function...not sure how to return the equivalent "name = Value" pair statements to the calling method. Essentially I am looking for:

                          def aMethod(self,** aDict):
                          undict(aDict)
                          .....
                          .....

                          SKN
                          Yes. Assuming you want your undict() function in a module:
                          [code=Python]# module unDict
                          def unDict(dd, dd0):
                          for key, value in dd.items():
                          exec "%s = %s" % (key, repr(value)) in dd0[/code]
                          Pass the globals() dictionary to the function:[code=Python]import unDict

                          dd = {'A': 'A string', 'B': 123.456, 'C': [1,2,3,4,5,6], 'D': 456}
                          unDict.unDict(d d, globals())
                          print A, B, C, D[/code]Output:
                          >>> A string 123.456 [1, 2, 3, 4, 5, 6] 456

                          Comment

                          • bvdet
                            Recognized Expert Specialist
                            • Oct 2006
                            • 2851

                            #14
                            Originally posted by hidrkannan
                            BV,

                            Also what is the purpose of "in None"...It gave me setitem attribute error..but when I remove "in None", it worked !!

                            Thanks

                            SKN
                            An unqualified exec is not allowed in my applications. "in globals()" would work also.

                            Comment

                            • hidrkannan
                              New Member
                              • Feb 2007
                              • 32

                              #15
                              Thanks BV for the clarification. I need to understand the use of globals()...
                              Thanks again..

                              SKN

                              Comment

                              Working...