Dictionary limitation

Alex Martelli alex at magenta.com
Fri Aug 4 09:36:12 EDT 2000


<pauljolly at my-deja.com> wrote in message news:8mean3$iam$1 at nnrp1.deja.com...
> Dear All,
>
> I have a query regarding dictionaries. Say I want to define a
> dictionary to do with fruits as follows:
>
> fruitDictionary={'apple':applePriceList, 'banana':bananaPriceList....}
>
> where the value refers to the name of a list of the prices of apples
> that I will add to as I find prices. Is there any way when I define the
> dictionary, that I can initialise the lists to zero length (ie temp=[])
> at the same time?

Well, you can do the definitions in two dictionaries:

def twodic(dic1,dic2,listofpairsofnames):
    for nam1,nam2 in listofpairsofnames:
        dic1[nam1]=dic2[nam2]=[]

But whether this satisfies your request depends on where you want
the variables to live.  If they're fields in a class-instance object, it's
fine:


twodic(fruitDict,self.__dict__,(('apple','applePricelist),(banana,'bananaPri
celist')))

But not all namespaces can be safely _modified_ as dictionaries.  The
docs are adamant about this not being kosher with locals() or vars(x) for
such x objects as modules, while apparently it's all right with globals(),
or,
presumably, for explicitly-fetched __dict__ references (I may be wrong on
this, and, if so, will gladly hear about it...!).

Generally, if you can frame your 'variables' as fields in a class-instance
object, then you're fine...


Alex






More information about the Python-list mailing list