Here are some ways to do this so that you can compare how it looks and choose what you like. I ordered them in a way that, in my opinion, is the most βpythonic,β and commented on the pros and cons, which may not be obvious at first glance:
Using collections.defaultdict :
import collections dict_x = collections.defaultdict(list) ... dict_x[key].append(value)
Pros: Probably the best performance. Cons: not available in Python 2.4.x.
Using dict().setdefault() :
dict_x = {} ... dict_x.setdefault(key, []).append(value)
Cons: Inefficient creation of unused list() s.
Using try ... except :
dict_x = {} ... try: values = dict_x[key] except KeyError: values = dict_x[key] = [] values.append(value)
Or:
try: dict_x[key].append(value) except KeyError: dict_x[key] = [value]
antak Oct 16 '12 at 1:19 2012-10-16 01:19
source share