I found code to undo a dictionary association.
def undict(dd, name_space=globals()):
for key, value in dd.items():
exec "%s = %s" % (key, repr(value)) in name_space
So if i run
>>dx= { 'a':1, 'b': 'B'} undict(dx)
I get
>>print A, B
1 B
Here, a=1 and b='B'
This works well enough for simple tasks and I understand the role of
globals() as the default names space, but creating local variables is
a problem. Also having no output arguemtns to undict() seems
counterintuitive. Also, the function fails if the key has spaces or
operand characters (-,$,/,%). Finally I know I will have cases where
not clearing (del(a,b)) each key-value pair might create problems in a
loop.
So I wonder if anyone has more elegant code to do the task that is
basically the opposite of creating a dictionary from a set of
globally assigned variables. And for that matter a way to create a
dictionary from a set of variables (local or global). Note I am not
simply doing and undoing dict(zip(keys,values)) 7 2108
On 30 Jul., 16:51, mmm <mdbol...@gmail.comwrote:
I found code to undo a dictionary association.
def undict(dd, name_space=globals()):
for key, value in dd.items():
exec "%s = %s" % (key, repr(value)) in name_space
So if i run
>dx= { 'a':1, 'b': 'B'} undict(dx)
I get>>print A, B
1 B
Here, a=1 and b='B'
This works well enough for simple tasks and I understand the role of
globals() as the default names space, but creating local variables is
a problem.
Python is lexically scoped. You can't create locals at runtime.
Also having no output arguemtns to undict() seems
counterintuitive. Also, the function fails if the key has spaces or
operand characters (-,$,/,%).
Python names can't have punctuation with the exception of underscores.
Finally I know I will have cases where
not clearing (del(a,b)) each key-value pair might create problems in a
loop.
So I wonder if anyone has more elegant code to do the task that is
basically the opposite of creating a dictionary from a set of
globally assigned variables. And for that matter a way to create a
dictionary from a set of variables (local or global). Note I am not
simply doing and undoing dict(zip(keys,values))
May I ask what's wrong with having namespaces in a language?
On 30 Lug, 16:51, mmm <mdbol...@gmail.comwrote:
I found code to undo a dictionary association.
def undict(dd, name_space=globals()):
* * for key, value in dd.items():
* * * * exec "%s = %s" % (key, repr(value)) in name_space
So if i run
>dx= { 'a':1, 'b': 'B'} undict(dx)
I get>>print A, B
1 B
Here, *a=1 and b='B'
This works well enough for simple tasks and I understand the role of
globals() as the default names space, but creating local variables is
a problem. Also having no output arguemtns to undict() seems
counterintuitive. *Also, the function fails if the key has spaces or
operand characters (-,$,/,%). *Finally I know I will have cases where
not clearing (del(a,b)) each key-value pair might create problems in a
loop.
So I wonder if anyone has more elegant code to do the task that is
basically the opposite of creating a dictionary from a set of
globally assigned variables. *And for that matter a way to create a
dictionary from a set of variables (local or global). *Note I am not
simply doing and *undoing dict(zip(keys,values))
Maybe you can use objects as pseudo name spaces and do sommething like
this:
>>class Scope(object):
def dict(self):
res = dict()
for k, v in self.__dict__.items(): res[k] = v
return res
def undict(self, dict):
for k,v in dict.items():
setattr(self, k, v )
>>myscope = Scope() myscope.undict(dict(A=1, B=2)) myscope.A
1
>>myscope.B
2
>>myscope.dict()
{'A': 1, 'B': 2}
>>>
Ciao
------
FB
mmm wrote:
I found code to undo a dictionary association.
def undict(dd, name_space=globals()):
for key, value in dd.items():
exec "%s = %s" % (key, repr(value)) in name_space
You are not undoing anything. You are updating globals() from another
dict. But why repr(value)? Without that, globals().update(dd) would
work. In 2.6?/3.0, replace 'dd' with '{a:b for a,b in dd.items()}
dd = { 'a':1, 'b': 'B'}
globals().update({a:b for a,b in dd.items()})
print(a,b)
# 1,B
>>>dx= { 'a':1, 'b': 'B'} undict(dx)
I get
>>>print A, B
1 B
Here, a=1 and b='B'
Don't fake interactive output. You would have to "print a,b". Above
gives a NameError.
This works well enough for simple tasks and I understand the role of
globals() as the default names space, but creating local variables is
a problem.
Within functions, yes. Just access the values in the dict.
Also having no output arguemtns to undict() seems
counterintuitive.
In Python, this is standard for functions that mutate.
Also, the function fails if the key has spaces or
operand characters (-,$,/,%).
Exec is tricky. Most people hardly ever use it.
Finally I know I will have cases where
not clearing (del(a,b)) each key-value pair might create problems in a
loop.
You cannot mutate a dict while iterating through it.
So I wonder if anyone has more elegant code to do the task that is
basically the opposite of creating a dictionary from a set of
globally assigned variables.
See above.
And for that matter a way to create a
dictionary from a set of variables (local or global).
You have to be more specific: there are {} displays and dict(args) call
and other methods. Read the manual.
tjr
And for that matter a way to create a
dictionary from a set of variables (local or global).
You have to be more specific: there are {} displays and dict(args) call
and other methods. *Read the manual.
My desire is to take a set of data items in an alpha-numeric range and
oput them into a dictionary
i.e.,
x1=1
x2=20
x3=33
to yield the dictionary
{ 'x1':1, 'x2':20, 'x3':33 }
without having to type in as above but instead invoke a function
maybe with syntax of
dd=make_dict('x1--x99')
En Wed, 30 Jul 2008 16:14:31 -0300, mmm <md******@gmail.comescribi�:
And for that matter a way to create a
dictionary from a set of variables (local or global).
You have to be more specific: there are {} displays and dict(args) call and other methods. Â*Read the manual.
My desire is to take a set of data items in an alpha-numeric range and
oput them into a dictionary
i.e.,
x1=1
x2=20
x3=33
to yield the dictionary
{ 'x1':1, 'x2':20, 'x3':33 }
without having to type in as above but instead invoke a function
dict(x1=1, x2=20, x3=33) does the same thing.
Or, do you mean you already have those names and values, perhaps mixed
with a lot more names, and want to extract only those starting with "x"
and following with a number?
result = {}
for name, value in vars(): # or locals().items(), or globals().items(), or
vars(some_module)
if name[0]=='x' and name[1:].isdigit():
result[name] = value
--
Gabriel Genellina
On Jul 30, 8:07*pm, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Wed, 30 Jul 2008 16:14:31 -0300, mmm <mdbol...@gmail.comescribi :
And for that matter a way to create a
dictionary from a set of variables (local or global).
You have to be more specific: there are {} displays and dict(args) call
and other methods. *Read the manual.
My desire is to take a set of data items in an alpha-numeric range and
oput them into a dictionary
i.e.,
x1=1
x2=20
x3=33
to yield *the dictionary
{ 'x1':1, 'x2':20, 'x3':33 }
without having to type in as above but instead invoke a function
dict(x1=1, x2=20, x3=33) does the same thing.
Or, do you mean you already have those names and values, perhaps mixed *
with a lot more names, and want to extract only those starting with "x" *
and following with a number?
result = {}
for name, value in vars(): # or locals().items(), or globals().items(), or *
vars(some_module)
* *if name[0]=='x' and name[1:].isdigit():
* * *result[name] = value
--
Gabriel Genellina
You can also use a blank class instance, and update its __dict__
member with the dictionary you design.
>>class A: pass
...
>>d= { 'x1': 0, 'x2': set( ) } A.__dict__
{'__module__': '__main__', '__doc__': None}
>>A.__dict__.update( d ) A.__dict__
{'x2': set([]), '__module__': '__main__', 'x1': 0, '__doc__': None}
>>A.x1
0
>>A.x2
set([])
>>>
I agree that locals( ) shouldn't necessarily be read-only, and I
believe it would extend the power of Python if it weren't.
Gabriel,
I meant the latter, so this helps
Or, do you mean you already have those names and values, perhaps mixed *
with a lot more names, and want to extract only those starting with "x" *
and following with a number?
result = {}
for name, value in vars(): # or locals().items(), or globals().items(), or *
vars(some_module)
* *if name[0]=='x' and name[1:].isdigit():
* * *result[name] = value
But I got an error with 'for name, value in vars():'
RuntimeError: dictionary changed size during iteration
I think globals() has the same problem, but globals.items() works. I
will need to read the docs to learn why '.items()' works but the
changing global dictionary problem makes sense. I assume I need to
use a non dynamic created list.
Sometimes I get the error about 'too many variables to unpack' (can
not consistently repeat the error however)
In any event, thanks for the suggestions, everyone.
Using a blank class for unpacking the dictionary makes the most sense,
for safety sake.
So you know the general issue is I want to switch between using
dictionaries for storing data items and simple variable names for
writing equations/formulas, So (a) and (b) below are preferred to (c)
for readability
(a) straight forward equation
y = b0 + b1*Age + b2*Size
(b) Class version
y = b0 + b1*x.Age + b2*x.Size
(c) Dictionary version
y = b0 + b1*dd.get('Age') + b2*dd.get('Size') This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Lyn |
last post by:
Hi,
I have a text control on a form which is bound to table field StartDate
which is in Date format. When updating the table record via the form, any
data entered into the StartDate control is...
|
by: Lyn |
last post by:
Hi,
In the BeforeUpdate event of a textbox control I have the following
simplified code:-
Private Sub StartDate_BeforeUpdate(Cancel As Integer)
MsgBox "StartDate Error -- Please Check and...
|
by: Wiktor Zychla |
last post by:
I am still trying to get the Undo function work on Internet Explorer editor
hosted as activex in my c# application.
Some time ago I've found a note at msdn that says "undo is not supported". I...
|
by: babylon |
last post by:
any facilities in csharp that can help me implmenting undo/redo in my
application?
thx
|
by: Christian H |
last post by:
Hello,
I've tried to find information about how to implement an Undo/Redo pattern.
This article describes such a pattern:
http://www.codeproject.com/csharp/PcObjectUndo.asp , but is a little bit...
|
by: GoogleEyeJoe |
last post by:
Dear ladies and gents,
I'm trying to determine whether the .NET Framework implements a means
of transactional processing without the need for a database.
Essentially, I'd like to enlist...
|
by: =?Utf-8?B?UmljaA==?= |
last post by:
Hello,
Does vb2005 have a built-in UnDo feature / object for applications so that I
can undo actions like other windows apps? Or do I have to write my own UnDo
routine?
If vb2005 does have a...
|
by: wizard of oz |
last post by:
Hi all,
I'm extending an Abstract Styled Document associated with a JTextPanel to
implement a syntax highlighting editor. This is all working just fine -
except for undo / redo.
The problem...
|
by: Jeremy |
last post by:
I'm working on an application that does some DOM manipulation. I want
to add a mechanism for "Undo" so that the user can revert to the
previous state after performing a mistaken action. Simple...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
| |