simple question using dictionary...
Question posted by: hidrkannan
(Newbie)
on
June 12th, 2008 01:21 AM
-
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)
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
|
|
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.
|
|
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
|
|
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:
-
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.....
|
|
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:
-
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
|
|
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:
-
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...
-
aDict = {}
-
aDict['abc'] = 1
-
aDict['defi'] = [2,4]
-
aDict['a'] = 5
-
aDict['bc'] = 'st'
-
aDict['zip'] = 12345
-
for kw in aDict:
-
#exec(str(a.keys()[index])+'='+str(a[key]))
-
exec(str(kw)+'="'+str(aDict[kw])+'"')
-
-
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
|
|
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
|
|
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
|
|
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....
|
|
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:
- for key, value in dd.items():
-
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.
|
|
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:
- for key, value in dd.items():
-
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
|
|
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
|
|
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:
- # module unDict
-
def unDict(dd, dd0):
-
for key, value in dd.items():
-
exec "%s = %s" % (key, repr(value)) in dd0
Pass the globals() dictionary to the function:
- import unDict
-
-
dd = {'A': 'A string', 'B': 123.456, 'C': [1,2,3,4,5,6], 'D': 456}
-
unDict.unDict(dd, globals())
-
print A, B, C, D
Output:
>>> A string 123.456 [1, 2, 3, 4, 5, 6] 456
|
|
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.
|
|
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
|
|
July 19th, 2008 02:40 AM
# 16
|
Re: simple question using dictionary...
Quote:
Yes. Assuming you want your undict() function in a module:
- # module unDict
-
def unDict(dd, dd0):
-
for key, value in dd.items():
-
exec "%s = %s" % (key, repr(value)) in dd0
Pass the globals() dictionary to the function:
- import unDict
-
-
dd = {'A': 'A string', 'B': 123.456, 'C': [1,2,3,4,5,6], 'D': 456}
-
unDict.unDict(dd, globals())
-
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
|
|
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
|
The keys in dictionary dd are now available as variable names.
|
|
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
|
|
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.
- >>> dd = {'a': 1, 'b': 2}
-
>>> a
-
Traceback (most recent call last):
-
File "<interactive input>", line 1, in ?
-
NameError: name 'a' is not defined
-
>>> def update_dict(dd_to_update, dd):
-
... dd_to_update.update(dd)
-
...
-
>>> update_dict(globals(), dd)
-
>>> a
-
1
-
>>>
|
|
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.
- >>> dd = {'a': 1, 'b': 2}
-
>>> a
-
Traceback (most recent call last):
-
File "<interactive input>", line 1, in ?
-
NameError: name 'a' is not defined
-
>>> def update_dict(dd_to_update, dd):
-
... dd_to_update.update(dd)
-
...
-
>>> update_dict(globals(), dd)
-
>>> a
-
1
-
>>>
|
If I use globals().update(dd) then the variables become global. I would like it to keep it local.
|
|
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.
- >>> import amodule
-
>>> amodule.update_dict(amodule.update_dict.func_globa ls, {'value1': 10.5, 'value2': 127.6})
-
>>> amodule.value1
-
10.5
-
>>>
|
|
July 22nd, 2008 04:22 AM
# 22
|
Re: simple question using dictionary...
Thanks again BV.
SKN
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
|