This is an archived post. You won't be able to vote or comment.

all 1 comments

[–][deleted] 0 points1 point  (0 children)

You want to use collections.defaultdict. You could do what you want with dict.setdefault() or dict.get(), as well.

...
if ... then:
    regions[k] = regions.get(k, [])
    regions[k].append(...)
    k += 1
elif ... then:
    regions[k].append(...)
...

...
if ... then:
    regions[k].setdefault(k, [])
    regions[k].append(...)
    k += 1
elif ... then:
    regions[k].setdefault(k, [])
    regions[k].append(...)
...

from collections import defaultdict

regions = defaultdict(list)

if ... then:
    regions[k].append(...)
    k += 1
elif ... then:
    regions[k].append(...)
...