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:
Post a Comment