I have a following problem. I have a list containing file names:
JavaScript
2
1
list_files = ["12_abc.txt", "12_ddd_xxx.pdf", "23_sss.xml", "23_adc.txt", "23_axx_yyy.pdf"]
2
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
2
1
dictionary = {"12": ["12_abc.txt", "12_ddd_xxx.pdf"], "23": ["23_sss.xml", "23_adc.txt", "23_axx_yyy.pdf"]}
2
What I tried so far:
JavaScript
5
1
dictionary = {}
2
for elem in list_files:
3
prefix = elem.split("_")[0]
4
dictionary[prefix] = elem
5
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
9
1
list_files = ["12_abc.txt", "12_ddd_xxx.pdf", "23_sss.xml", "23_adc.txt", "23_axx_yyy.pdf"]
2
3
dictionary = {}
4
for f in list_files:
5
prefix = f.split('_')[0] # or prefix, _ = f.split('_', maxsplit=1)
6
dictionary.setdefault(prefix, []).append(f)
7
8
print(dictionary)
9
Prints:
JavaScript
2
1
{'12': ['12_abc.txt', '12_ddd_xxx.pdf'], '23': ['23_sss.xml', '23_adc.txt', '23_axx_yyy.pdf']}
2
EDIT: Added maxsplit=1
variant, thanks @Ma0