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

Jeff Shannon jeff@ccvcorp.com
Thu May 15 14:07:29 2003


Jeff Kowalczyk wrote:

>I need to conditionally append an id with setdefault(k,v[id]) to either:
>-  the list that is the existing value v for key k,
>- or start a new list v a single value of id.
>
>Can anyone suggest a more efficient and compact syntax to accomplish this?
>
>OrderDates = {}
>for OrderDate, OrderID in Orders:
>    if OrderDates.has_key(OrderDate):
>        OrderDates.setdefault(OrderDate,OrderDates[OrderDate].append(OrderID))
>    else:
>        OrderDates.setdefault(OrderDate,[OrderID,])
>    print OrderDates
>  
>

You don't need setdefault(), you only need get().

for OrderDate, OrderID in Orders:
    OldValue = OrderDates.get(OrderDate, [])
    OrderDates[OrderDate] = OldValue.append(OrderID)

I used two lines above for the sake of clarity, so that it's a little 
easier to see what's happening.  The dict method get() will return the 
value associated with the first argument (OrderDate) if there is such a 
value, and will return the second argument if there is no such value. 
 So my first line will give either the previous list of orders for that 
date, or an empty list.  Either way, I append the current order ID to 
the list and put it back in the dictionary.  This can all be done in a 
single line, as well --

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.

Jeff Shannon
Technician/Programmer
Credit International