Inline Calculation of Dictionary Values

++imanshu himanshu.garg at gmail.com
Wed Apr 21 16:42:32 CEST 2010


On Apr 21, 7:31 pm, Dave Angel <da... at ieee.org> wrote:
> ++imanshu wrote:
> > Hi,
>
> >      Is it possible to something along these lines in python :-
>
> > map = {
> > 'key1': f(),
> > 'key2': modify_state(); val = f(); restore_state(); val,
> > 'key3': f(),
> > }
>
> >       For 'key2' I want to store the value returned by f() but after
> > modifying the state. Do we have something like a "bare block". I am
> > trying to avoid this :-
>
> > def f2():
> >      modify_state()
> >      val = f()
> >      restore_state()
> >      return val
>
> > map = {
> > 'key1': f(),
> > 'key2': f2()
> > 'key3': f(),
> > }
>
> > Thank You,
> > Himanshu
>
> How about something like:
>
> mymap = {
> 'key1': f(),
> 'key2': [modify_state(), f(), restore_state()][1],
> 'key3': f(),
>
> }
>
> This builds a list of three values, and uses only the [1] item from the
> list.
>
> DaveA

This is cool. I'll use it.

Thank You,
Himanshu



More information about the Python-list mailing list