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

Reggie Dugard reggie@merfinllc.com
Thu May 15 13:40:02 2003


Jeff,

I think this will do the trick for you:

OrderDates = {}
for OrderDate, OrderID in Orders:
	OrderDates.setdefault(OrderDate, []).append(OrderID)
print OrderDates

HTH

On Thu, 2003-05-15 at 10:05, 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
> 
> I'm trying to build up a dictionary of OrderIDs keyed to a date. The iteration part is
> pseudocode, but my actual code builds several dictionaries this way, and I want to
> simplify the implementation as much as possible.
> 
>  {'05-02-2003' : ['123456','123457','123458','123459'],
>   '05-03-2003' : ['123460''123460','123460','123460','123460'],}
> 
> Thanks.
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Reggie