I have found myself writing code like this fairly often:
nums = {}
allpngs = [ii for ii in os.listdir() if '.png' in ii]
for png in allpngs:
regex = r'(.*)(\d{4,})\.png'
prefix = re.search(regex, png).group(1)
mynum = int(re.search(regex, png).group(2))
if prefix in nums.keys():
nums[prefix].append(mynum)
else:
nums[prefix] = [mynum]
Essentially, I'm wanting to create a dictionary of lists where the keys are not known ahead of time. This requires the if statement you see at the bottom of the for loop. I seem to write this pretty frequently, so I'm wondering if there's a shorter / more pythonic way of doing this.
To be clear, what I have works fine, but it would be nice if I could do it in fewer lines and still have it be readable and apparent what's happening.
Thanks.