Skip to content
Advertisement

how to add file names into dictionary based on their prefix?

I have a following problem. I have a list containing file names:

JavaScript

I need to add them into dictionary based on their prefix number, i.e. 12 and 23. Each value of the dictionary should be a list containing all files with the same prefix. Desired output is:

JavaScript

What I tried so far:

JavaScript

However this gives me the result {'12': '12_ddd_xxx.pdf', '23': '23_axx_yyy.pdf'}. How can I add my elem into a list within the loop, please?

Advertisement

Answer

Try:

JavaScript

Prints:

JavaScript

EDIT: Added maxsplit=1 variant, thanks @Ma0

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement