[Tutor] Re: How to accomplish Dict setdefault(key, (append to existing value list) or (start new list) )?

Jeff Kowalczyk jtk@yahoo.com
Thu May 15 14:51:02 2003


Jeff Shannon wrote:
> for OrderDate, OrderID in Orders:
>     OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID)
> I've found get() to be invaluable any time that I want to organize a
> sequence into "buckets" (as you're doing) or count occurrences of something.

That's really slick, I like it.
I'm having some trouble with the one-line version though:

Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
>>> Orders = (('2003-05-14','Ord1234'),('2003-05-14','Ord1235'),
                        ('2003-05-15','Ord1236'),('2003-05-16','Ord1237'))
>>> OrderDates = {}
>>> for OrderDate, OrderID in Orders:
...        OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID)
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
AttributeError: 'NoneType' object has no attribute 'append'
>>> print OrderDates.get('2003-05-14',[])
None

Did I miss something?

I seem to be having a that problem (failed late evaluation to list type) a lot lately.