473,545 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"Extracting " a dictionary

Hello,

I'm quite new to Python, and since a not-so-superficial look into the
docs didn't answer my question (although it still feels quite basic), I
decided to turn to this place:

Is there a way to 'extract' a dictionary into the current namespace?
That is, if you have
{'foo' : 23, 'bar' : 42}
you would get a variable foo with value 23 and a variable bar with value
42? Such a function would of course only work on string keys and would
probably have to check that, but still, it sounds practical enough that
surely someone else thought of it before.

Daniel

Jul 18 '05 #1
16 2371
Daniel Klein wrote:
Is there a way to 'extract' a dictionary into the current namespace?
That is, if you have
{'foo' : 23, 'bar' : 42}
you would get a variable foo with value 23 and a variable bar with value
42? Such a function would of course only work on string keys and would
probably have to check that, but still, it sounds practical enough that
surely someone else thought of it before.

vars = {'foo': 23, 'bar': 42}
locals().update (vars)
foo 23 bar

42
Jul 18 '05 #2
Leif K-Brooks wrote:
Daniel Klein wrote:
Is there a way to 'extract' a dictionary into the current namespace?
That is, if you have
{'foo' : 23, 'bar' : 42}
you would get a variable foo with value 23 and a variable bar with
value 42? Such a function would of course only work on string keys and
would probably have to check that, but still, it sounds practical
enough that surely someone else thought of it before.


>>> vars = {'foo': 23, 'bar': 42}
>>> locals().update (vars)
>>> foo 23 >>> bar

42


Except note from this page
http://docs.python.org/lib/built-in-...built-in-funcs that
"""
locals()

Update and return a dictionary representing the current local symbol
table. Warning: The contents of this dictionary should not be
modified; changes may not affect the values of local variables used by
the interpreter.
"""

So Don't Do That.

-Peter
Jul 18 '05 #3
Am Montag, 17. Mai 2004 21:34 schrieb Leif K-Brooks:
>>> locals().update (vars)


From the documentation:

"""
locals()

Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes may
not affect the values of local variables used by the interpreter.
"""

Heiko.

Jul 18 '05 #4
The result of modifying locals() is undefined.

Jeff

Jul 18 '05 #5
Daniel Klein <br****@gmx.a t> wrote in message news:<ma******* *************** **************@ python.org>...
Is there a way to 'extract' a dictionary into the current namespace?
That is, if you have
{'foo' : 23, 'bar' : 42}
you would get a variable foo with value 23 and a variable bar with value
42? Such a function would of course only work on string keys and would
probably have to check that, but still, it sounds practical enough that
surely someone else thought of it before.

Daniel


The most straightforward way I know is
d = {'foo': 23, 'bar': 42}
globals().updat e(d)
print foo, bar 23 42

This only works with globals, though - there's a corresponding
locals(), but unfortunately the docs say updating it's a no-no - the
dict returned could be a copy of the real locals dict (or the real
locals might not be in a dict at all). The interpreter is free to
ignore changes to the dictionary that locals() returns (although it
happens not to in CPython at the moment, that's an implementation
detail).

Even with the globals, it's a bit magical and could end up overwriting
names that match a key in the dictionary (it would be irritating if
one of the keys was "file" or "list").

Maybe a cleaner way to do essentially what you want is to use the
martellibot's Bunch recipe:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52308

This would allow you to do:
class Bunch: def __init__(self, **kwds):
self.__dict__.u pdate(kwds)

d = {'foo': 23, 'bar': 42}
bunch = Bunch(**d)
print bunch.foo, bunch.bar

23 42

This means you're not clobbering the global or local namespace with
arbitrary bindings, and you could have lots of Bunch instances for
different collections of bindings.

Cheers,
xtian
Jul 18 '05 #6
Daniel Klein wrote:
Hello,

I'm quite new to Python, and since a not-so-superficial look into the
docs didn't answer my question (although it still feels quite basic), I
decided to turn to this place:

Is there a way to 'extract' a dictionary into the current namespace?
That is, if you have
{'foo' : 23, 'bar' : 42}
you would get a variable foo with value 23 and a variable bar with value
42? Such a function would of course only work on string keys and would
probably have to check that, but still, it sounds practical enough that
surely someone else thought of it before.

Daniel


Is this illegal?
import __main__
d = {'foo':'oof','b ar':'rab','baz' :'zab'}
for k,v in d.items(): .... setattr(__main_ _, k, v)
.... foo,bar,baz

('oof', 'rab', 'zab')

--
Jason
Jul 18 '05 #7
Jason Mobarak wrote:
Daniel Klein wrote:
Is there a way to 'extract' a dictionary into the current namespace?


Is this illegal?
>>> import __main__
>>> d = {'foo':'oof','b ar':'rab','baz' :'zab'}
>>> for k,v in d.items(): ... setattr(__main_ _, k, v)
... >>> foo,bar,baz

('oof', 'rab', 'zab')


No, but it will need to be changed for the module's name, and won't work
at all in a local namespace (like a function).
Jul 18 '05 #8
Heiko Wundram wrote:
Am Montag, 17. Mai 2004 21:34 schrieb Leif K-Brooks:
>>> locals().update (vars)


From the documentation:

"""
locals()

Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes may
not affect the values of local variables used by the interpreter.
"""


Thanks for pointing that out, I was a bit lazy with TFM. Please ignore
my advice.
Jul 18 '05 #9
Daniel Klein wrote:
Hello,

I'm quite new to Python, and since a not-so-superficial look into the
docs didn't answer my question (although it still feels quite basic), I
decided to turn to this place:

Is there a way to 'extract' a dictionary into the current namespace?
That is, if you have
{'foo' : 23, 'bar' : 42}
you would get a variable foo with value 23 and a variable bar with value
42? Such a function would of course only work on string keys and would
probably have to check that, but still, it sounds practical enough that
surely someone else thought of it before.

Daniel


How about this:

In [1]: d = {'foo' : 23, 'bar' : 42}

In [2]: for item in d.items():
...: exec "%s = %d" % item
...:

In [3]: foo
Out[3]: 23

In [4]: bar
Out[4]: 42

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
23826
by: Mark DuPrey | last post by:
I've got a script in an ASP page that is supposed to extract certain files from a zip file, move them, create a new zip with the moved files and then make a self-extracting archive out of the new zip file. I'm doing this using wshShell.Exec, the WinZip command line tool and zip2exe.exe from the pkware suite (because WinZip's command line...
0
7415
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7928
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7775
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5997
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4963
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3470
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1902
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1030
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
726
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.