-
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
21 2365
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.
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
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.....
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
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
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
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
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....
bvdet 2,851
Expert Mod 2GB
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.
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
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
bvdet 2,851
Expert Mod 2GB
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
bvdet 2,851
Expert Mod 2GB
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.
Thanks BV for the clarification. I need to understand the use of globals()...
Thanks again..
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
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
bvdet 2,851
Expert Mod 2GB
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.
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
bvdet 2,851
Expert Mod 2GB
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
-
>>>
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.
bvdet 2,851
Expert Mod 2GB
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_globals, {'value1': 10.5, 'value2': 127.6})
-
>>> amodule.value1
-
10.5
-
>>>
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Paulo Pinto |
last post by:
Hi,
does anyone know of a Python package that
is able to load XML like the XML::Simple
Perl package does?
For those that don't know it, this package
maps the XML file to a dictionary.
|
by: Fuzzyman |
last post by:
There have been a couple of config file 'systems' announced recently,
that focus on building more powerful and complex configuration files.
ConfigObj is a module to enable you to much more *simply*...
|
by: Eric S. Johansson |
last post by:
I have an application where I need a very simple database, effectively a
very large dictionary. The very large dictionary must be accessed from
multiple processes simultaneously. I need to be...
|
by: Chris Dunaway |
last post by:
I have created a simple Extender Provider and when I drop it onto a
form, it appears in the component tray, but none of the controls it is
supposed to provide a property for show the property in...
|
by: pamela fluente |
last post by:
Hi, please find below a very simple code snippet which is giving me
the following error:
System.Runtime.Serialization.SerializationException was unhandled
Message="The constructor to deserialize...
|
by: =?Utf-8?B?bWFnZWxsYW4=?= |
last post by:
Hi,
I'd appreciae any advice on how to do this in VB 2005.
I have a simple array;e..g, a list of States, e.g., CA, WA, ID, AL, and
etc...
I like to determine how many unqiue "States" are...
|
by: Jonathan Fine |
last post by:
Hello
I want to serialise a dictionary, whose keys and values are ordinary strings
(i.e. a sequence of bytes).
I can of course use pickle, but it has two big faults for me.
1. It should not...
|
by: isinc |
last post by:
I have an assignment that I'm working on and am having trouble. Not too familiar with graphics. Any help/guidance would be much appreciated to see if what I have so far is okay and what I should do...
|
by: skazhy |
last post by:
hi, i am new to python, so i've a really simple question about
dictionaries.
if i have a dictionary and I make have an input after it (to input
numbers) can i get the key of value that was in...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
| |