Tuesday, August 9, 2011

Python: add an entry to an dict of arrays or create one if it doesn't exist

I frequently am working with dictionaries of arrays and want to add an element to an existing array, or create one if it doesn't exist. There is a neat, if not particularly easy to understand, way to do this with setdefault:

result = {}
for thisthing in alist:
   result.setdefault(thisthing.somekey, []).append(thisthing.somevalue)
So you will end up with something like:
{'key1':[value1, value2], 'key2': [value3]}

No comments: