[Tutor] Would like some help

luke rabidpoobear at gmail.com
Mon Aug 15 17:27:32 CEST 2005

I believe what's happening in the second example is that you can combine
>>>d2 = {'hello':1,'hi':2}
>>>print d2.items()

so in the second example you can just pass it a list of elements (.items())
and it will concatenate (append?) these to the new dictionary.
hope that helps.


----- Original Message -----
From: "Howard Kao" <fatearthling at gmail.com>
To: <tutor at python.org>
Sent: Monday, August 15, 2005 6:32 AM
Subject: [Tutor] Would like some help

> ----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
>     d.update(kwds)
>     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.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list