Learning about dictionaries

Andrei project5 at redrival.net
Fri Apr 16 13:52:42 EDT 2004


Thomas Philips wrote on Friday 16 April 2004 18:50:

> I'm teaching myself python and in the course of playing around with
> dictionaries, I tried to create the following trivial dictionary
> 
> {1:'one', 2:'two'}
> 
> So I entered
>>>> dict(1='one',2='two')
> SyntaxError: keyword can't be an expression

Try doing 1 = 'one' in the interactive interpreter. Does it work? Nope. Did
you expect it to work? (Hopefully not :).) So obviously it doesn't work
inside a function call neither.

> Out of curiosity, I tried
>>>> dict(one=1,two=2)
> {'two': 2, 'one': 1}

Bingo :). Python has a special construct for functions which accept any
numbers of keyword arguments (these are arguments which have the form of
<name>=<object>, as opposed to non-keyword arguments which are just
<object>). This means that you don't have to specify the parameters in
advance like this:

>>> def myfunc(a, b):
...     pass

Instead, you allow any number of parameters to be passed to the function
using '**'

>>> def myfunc(**kwds):
...     print kwds 
...     # kwds is a dictionary containing all parametername-value pairs
...
>>> myfunc(a='5', b=6, c=True)
{'a': '5', 'c': True, 'b': 6}

You can modify myfunc now very easily to behave like dict() in this
particular case:

>>> def myfunc(**kwds):
...     return kwds
...
>>> mydict =  myfunc(a='5', b=6, c=True)
>>> print mydict
{'a': '5', 'c': True, 'b': 6}

The method Wes specified for creating dictionaries is more useful and usable
IMO than dict() with keyword parameters.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.



More information about the Python-list mailing list