[Tutor] Would like some help

Kent Johnson kent37 at tds.net
Mon Aug 15 19:00:38 CEST 2005


Howard Kao wrote:
> ----Directly Quoted From the Python Cookbook----
> Once you get into the swing of Python, you may find yourself
> constructing a lot of dictionaries. However, the standard way, also
> known as a dictionary display, is just a smidgeon more cluttered than
> you might like, due to the need to quote the keys. For example:
> 
> data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
> When the keys are identifiers, there's a cleaner way:
> 
> def makedict(**kwargs):
>     return kwargs
> data = makedict(red=1, green=2, blue=3)

This recipe is obsolete; since Python 2.3 (at least) you can pass keyword args directly to the dict() constructor:
data = dict(red=1, green=2, blue=3)

> You might also choose to forego some simplicity to gain more power.
> For example:
> 
> def dodict(*args, **kwds):
>     d = {}
>     for k, v in args: d[k] = v
>     d.update(kwds)
>     return d
> tada = dodict(*data.items(  ), yellow=2, green=4)

This can now be written as 
tada = dict(data, yellow=2, green=4)

Kent



More information about the Tutor mailing list