[Tutor] Would like some help

Howard Kao fatearthling at gmail.com
Mon Aug 15 13:32:41 CEST 2005

----Directly Quoted From the Python Cookbook----
1.3 Constructing a Dictionary Without Excessive Quoting
Credit: Brent Burley

1.3.1 Problem
You'd like to construct a dictionary without having to quote the keys. 

1.3.2 Solution
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)
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
    return d
tada = dodict(*data.items(  ), yellow=2, green=4)
----End Quote----

Hi guys, 
Above is a direct cut & paste from the book (hope I am not violating
any thing...).  I've read the Python docs and can understand the first
def example ok, I suppose.  However I would like some detailed
explaination about the second example, the dodict one.  How exactly
does it work?  It just puzzles me why this would be more powerful or
better, even though I can understand and agree that re-writting
programs makes good practice.  In fact that's what I am looking for
from reading this book.  Just hope someone can walk me through this
simple code.  Thanks for the help.

More information about the Tutor mailing list