Pythonic Way to Add New Keys into Dictionary of Lists

Question:

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.

Asked By: jippyjoe4

||

Answers:

You can use dict.setdefault:


...

nums.setdefault(prefix, []).append(mynum)

...
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.