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

Jeff Kowalczyk jtk@yahoo.com
Thu May 15 13:09:02 2003


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.