473,402 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

simple question using dictionary...

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)
  25.  
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
Jun 12 '08 #1
21 2365
woooee
43
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.
Jun 12 '08 #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.

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

SKN
Jun 12 '08 #3
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
  6.  
Hope i helped.....
Jun 12 '08 #4
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.  
  10.  
That will do the job!!!

Elias
Jun 12 '08 #5
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.  
  10.  
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
  12.  
Please comment.

SKN
Jun 12 '08 #6
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
Jun 12 '08 #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

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
Jun 12 '08 #8
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....
Jun 12 '08 #9
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:
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.
Jun 12 '08 #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:
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
Jun 12 '08 #11
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
Jun 12 '08 #12
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:
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
Jun 12 '08 #13
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.
Jun 12 '08 #14
Thanks BV for the clarification. I need to understand the use of globals()...
Thanks again..

SKN
Jun 12 '08 #15
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
Jul 19 '08 #16
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
Expand|Select|Wrap|Line Numbers
  1. globals().update(dd)
The keys in dictionary dd are now available as variable names.
Jul 19 '08 #17
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
Jul 19 '08 #18
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.
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. >>> 
Jul 19 '08 #19
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.
Jul 19 '08 #20
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.
Expand|Select|Wrap|Line Numbers
  1. >>> import amodule
  2. >>> amodule.update_dict(amodule.update_dict.func_globals, {'value1': 10.5, 'value2': 127.6})
  3. >>> amodule.value1
  4. 10.5
  5. >>> 
Jul 20 '08 #21
Thanks again BV.

SKN
Jul 22 '08 #22

Sign in to post your reply or Sign up for a free account.

Similar topics

13
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.
4
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*...
10
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...
1
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...
6
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...
6
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...
9
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...
7
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...
6
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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...
0
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...
0
tracyyun
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...
0
agi2029
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,...
0
isladogs
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.