Sign In | Register Now About Bytes | Help | Site Map
Connecting Tech Pros Worldwide

simple question using dictionary...

Question posted by: hidrkannan (Newbie) on June 12th, 2008 01:21 AM
Expand|Select|Wrap|Line Numbers
  1. aDict = {}
  2. aDict['a'] = 5
  3. aDict['bc'] = 'st'
  4. aDict['zip'] = 12345
  5.  
  6.  
  7.  
  8. def outputMethod(**aDict):
  9.     print aDict['a']
  10.     print aDict['bc']
  11.     print aDict['zip']
  12.     return
  13. def outputMethod1(**aDict):
  14.     for key in aDict:
  15.         ...
  16.         ...
  17.     print a
  18.     print bc
  19.     print zip
  20.     return
  21.  
  22.  
  23. outputMethod(**aDict)
  24. outputMethod1(**aDict)


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...but not sure how to define the "keys" as variable names?

Thanks in advance.

SKN
woooee's Avatar
woooee
Newbie
24 Posts
June 12th, 2008
02:43 AM
#2

Re: simple question using dictionary...
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.

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
June 12th, 2008
04:15 AM
#3

Re: simple question using dictionary...
Quote:
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

Reply
Elias Alhanatis's Avatar
Elias Alhanatis
Member
47 Posts
June 12th, 2008
06:40 AM
#4

Re: simple question using dictionary...
Hello!

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

Expand|Select|Wrap|Line Numbers
  1. aDict={'w':1,'e':2,'r':3}
  2. index=0
  3. for key in aDict.keys():
  4.     exec(str(aDict.keys()[index])+'='+str(aDict[key]))
  5.     index+=1


Hope i helped.....

Reply
Elias Alhanatis's Avatar
Elias Alhanatis
Member
47 Posts
June 12th, 2008
06:48 AM
#5

Re: simple question using dictionary...
Rushed to post the reply but forgot the case of values being strings!!!!!
Here is the improved ( yet still simple or 'naive' ) suggestion:

Expand|Select|Wrap|Line Numbers
  1. a={'w':1,'e':'rt6','r':3}
  2. index=0
  3. for key in a.keys():
  4.     if type(a[key])!=type(""):
  5.         exec(str(a.keys()[index])+'='+str(a[key]))
  6.     else:
  7.         exec(str(a.keys()[index])+'="'+str(a[key])+'"')
  8.     index+=1
  9.  


That will do the job!!!

Elias

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
June 12th, 2008
12:19 PM
#6

Re: simple question using dictionary...
Quote:
Rushed to post the reply but forgot the case of values being strings!!!!!
Here is the improved ( yet still simple or 'naive' ) suggestion:

Expand|Select|Wrap|Line Numbers
  1. a={'w':1,'e':'rt6','r':3}
  2. index=0
  3. for key in a.keys():
  4.     if type(a[key])!=type(""):
  5.         exec(str(a.keys()[index])+'='+str(a[key]))
  6.     else:
  7.         exec(str(a.keys()[index])+'="'+str(a[key])+'"')
  8.     index+=1
  9.  


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...

Expand|Select|Wrap|Line Numbers
  1. aDict = {}
  2. aDict['abc'] = 1
  3. aDict['defi'] = [2,4]
  4. aDict['a'] = 5
  5. aDict['bc'] = 'st'
  6. aDict['zip'] = 12345
  7. for kw in aDict:
  8.     #exec(str(a.keys()[index])+'='+str(a[key]))
  9.     exec(str(kw)+'="'+str(aDict[kw])+'"')
  10.  
  11. print a, bc,zip,abc, defi


Please comment.

SKN

Last edited by hidrkannan : June 12th, 2008 at 12:26 PM. Reason: Not seem to work
Reply
Elias Alhanatis's Avatar
Elias Alhanatis
Member
47 Posts
June 12th, 2008
01:06 PM
#7

Re: simple question using dictionary...
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

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
June 12th, 2008
01:30 PM
#8

Re: simple question using dictionary...
Quote:
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

Reply
Elias Alhanatis's Avatar
Elias Alhanatis
Member
47 Posts
June 12th, 2008
01:55 PM
#9

Re: simple question using dictionary...
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....

Reply
bvdet's Avatar
bvdet
Expert
1,143 Posts
June 12th, 2008
03:28 PM
#10

Re: simple question using dictionary...
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:
Expand|Select|Wrap|Line Numbers
  1. for key, value in dd.items():
  2.     exec "%s = %s" % (key, repr(value)) in None
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.

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
June 12th, 2008
04:14 PM
#11

Re: simple question using dictionary...
Quote:
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:
Expand|Select|Wrap|Line Numbers
  1. for key, value in dd.items():
  2.     exec "%s = %s" % (key, repr(value)) in None
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

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
June 12th, 2008
04:38 PM
#12

Re: simple question using dictionary...
Quote:
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

Reply
bvdet's Avatar
bvdet
Expert
1,143 Posts
June 12th, 2008
04:52 PM
#13

Re: simple question using dictionary...
Quote:
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:
Expand|Select|Wrap|Line Numbers
  1. # module unDict
  2. def unDict(dd, dd0):
  3.     for key, value in dd.items():
  4.         exec "%s = %s" % (key, repr(value)) in dd0

Pass the globals() dictionary to the function:
Expand|Select|Wrap|Line Numbers
  1. import unDict
  2.  
  3. dd = {'A': 'A string', 'B': 123.456, 'C': [1,2,3,4,5,6], 'D': 456}
  4. unDict.unDict(dd, globals())
  5. print A, B, C, D
Output:
>>> A string 123.456 [1, 2, 3, 4, 5, 6] 456

Reply
bvdet's Avatar
bvdet
Expert
1,143 Posts
June 12th, 2008
04:59 PM
#14

Re: simple question using dictionary...
Quote:
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.

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
June 12th, 2008
11:22 PM
#15

Re: simple question using dictionary...
Thanks BV for the clarification. I need to understand the use of globals()...
Thanks again..

SKN

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
July 19th, 2008
02:40 AM
#16

Re: simple question using dictionary...
Quote:
Yes. Assuming you want your undict() function in a module:
Expand|Select|Wrap|Line Numbers
  1. # module unDict
  2. def unDict(dd, dd0):
  3.     for key, value in dd.items():
  4.         exec "%s = %s" % (key, repr(value)) in dd0

Pass the globals() dictionary to the function:
Expand|Select|Wrap|Line Numbers
  1. import unDict
  2.  
  3. dd = {'A': 'A string', 'B': 123.456, 'C': [1,2,3,4,5,6], 'D': 456}
  4. unDict.unDict(dd, globals())
  5. print A, B, C, D
Output:
>>> A string 123.456 [1, 2, 3, 4, 5, 6] 456



Is there any other alternative to do this instead of using exec. I am hearing the use of exec is not a good practice as it is a dowside factor for performance?

Thanks in Advance
SKN

Reply
bvdet's Avatar
bvdet
Expert
1,143 Posts
July 19th, 2008
01:38 PM
#17

Re: simple question using dictionary...
Quote:
Is there any other alternative to do this instead of using exec. I am hearing the use of exec is not a good practice as it is a dowside factor for performance?

Thanks in Advance
SKN
Expand|Select|Wrap|Line Numbers
  1. globals().update(dd)
The keys in dictionary dd are now available as variable names.

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
July 19th, 2008
07:20 PM
#18

Re: simple question using dictionary...
Thanks BV.

I suppose, if I use with in a method/function, then I can use locals.update(dd) instead of globals().update(dd).
Please correct me if I am wrong.

SKN

Reply
bvdet's Avatar
bvdet
Expert
1,143 Posts
July 19th, 2008
08:03 PM
#19

Re: simple question using dictionary...
Quote:
Thanks BV.

I suppose, if I use with in a method/function, then I can use locals.update(dd) instead of globals().update(dd).
Please correct me if I am wrong.

SKN
You cannot update the local dictionary - it's not allowed. It can be done by passing the global dictionary to the function for updating.
Expand|Select|Wrap|Line Numbers
  1. >>> dd = {'a': 1, 'b': 2}
  2. >>> a
  3. Traceback (most recent call last):
  4.   File "<interactive input>", line 1, in ?
  5. NameError: name 'a' is not defined
  6. >>> def update_dict(dd_to_update, dd):
  7. ...     dd_to_update.update(dd)
  8. ...     
  9. >>> update_dict(globals(), dd)
  10. >>> a
  11. 1
  12. >>> 

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
July 19th, 2008
11:54 PM
#20

Re: simple question using dictionary...
Quote:
You cannot update the local dictionary - it's not allowed. It can be done by passing the global dictionary to the function for updating.
Expand|Select|Wrap|Line Numbers
  1. >>> dd = {'a': 1, 'b': 2}
  2. >>> a
  3. Traceback (most recent call last):
  4.   File "<interactive input>", line 1, in ?
  5. NameError: name 'a' is not defined
  6. >>> def update_dict(dd_to_update, dd):
  7. ...     dd_to_update.update(dd)
  8. ...     
  9. >>> update_dict(globals(), dd)
  10. >>> a
  11. 1
  12. >>> 

If I use globals().update(dd) then the variables become global. I would like it to keep it local.

Reply
bvdet's Avatar
bvdet
Expert
1,143 Posts
July 20th, 2008
02:03 PM
#21

Re: simple question using dictionary...
Quote:
If I use globals().update(dd) then the variables become global. I would like it to keep it local.
It could be encapsulated in a module. The global namespace for a function is always the module in which it was defined.
Expand|Select|Wrap|Line Numbers
  1. >>> import amodule
  2. >>> amodule.update_dict(amodule.update_dict.func_globa  ls, {'value1': 10.5, 'value2': 127.6})
  3. >>> amodule.value1
  4. 10.5
  5. >>> 

Reply
hidrkannan's Avatar
hidrkannan
Newbie
30 Posts
July 22nd, 2008
04:22 AM
#22

Re: simple question using dictionary...
Thanks again BV.

SKN

Reply
Reply
Not the answer you were looking for? Post your question . . .
189,282 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Latest Articles: Read & Comment
Top Python Forum Contributors