[Tutor] Re: How to accomplish Dict setdefault(key, (append to
existing value list) or (start new list) )?
Jeff Shannon
jeff@ccvcorp.com
Thu May 15 16:53:02 2003
Kristoffer Erlandsson wrote:
>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:
>
>
Why, so it does. You'd think I'd know by now that I shouldn't post
untested code. Ah well.
So, this leaves us with a couple of options. One is to go back to doing
this in several lines, but making the append() into a separate step:
for OrderDate, OrderID in Orders:
current = OrderDates.get(OrderDate, [])
current.append(OrderID)
OrderDates[OrderDate] = current
Another option is to follow the old maxim that "It's easier to ask
forgiveness than permission", and to directly catch the KeyError that
happens when we try to access a nonexistent key:
for OrderDate, OrderID in Orders:
try:
OrderDates[OrderDate].append(OrderID)
except KeyError:
OrderDates[OrderDate] = [OrderID]
This calls append() directly on the dictionary contents. If nothing is
found for that OrderDate, then we get a KeyError exception, and when
that happens we add a new list to the dictionary that contains the
current OrderID.
Jeff Shannon
Technician/Programmer
Credit International