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

Kristoffer Erlandsson krier115@student.liu.se
Thu May 15 15:35:02 2003


On Thu, May 15, 2003 at 02:44:25PM -0400, Jeff Kowalczyk wrote:
> 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.
> 

Appending to a list doesn't return anything, it changes the list
directly and returns None. So what

OrderDates[OrderDate] = OrderDates.get(OrderDate, []).append(OrderID)

does is to set OrderDates[OrderDate] to the returned value of append,
which is none:

>>> OrderDates
{'2003-05-14': None}

So when you try next time, the get returns None, and you try to append
to that.

HTH

-- 
Kristoffer Erlandsson
E-mail:  krier115@student.liu.se
ICQ#:    378225