undo a dictionary

castironpi castironpi at gmail.com
Thu Jul 31 04:29:58 CEST 2008


On Jul 30, 8:07 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Wed, 30 Jul 2008 16:14:31 -0300, mmm <mdbol... at gmail.com> escribi :
>
>
>
> >> > 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.



More information about the Python-list mailing list