Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pythonic Way to Add New Keys into Dictionary of Lists

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks.

>Solution :

You can use dict.setdefault:


...

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

...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading