I'm relatively new to Python, actually to programming as a whole. Unfortunately, I have not been able to find an answer to my question on the forum yet.
I have a list with different file extensions, the file extensions occur multiple times. See example here:
extensions = ["JPG", "XLSX", "MP3", "PDF", "EXE", "PY", "XLSX", "DOCX", "JPG", "PPTX"]
I want to create a new list of dictionaries using the above list. It should look like this:
dicts = [{"Extension": "py", "Count": 1}, {"Extension": "docx", "Count": 1}]
My plan is to iterate over the list and to append the file extension to the new list as a new dictionary as shown in the line of code above. If the extension already exists as a dictionary in the list of dictionaries, only the index ["Count"] of the matching dictionary should be incremented with +=1. I have written the following code, but it does not work.
I know that the empty extensionlist within the function is one problem, but still I don't get it to work as intended. I would appreciate any help.
extensions = ["JPG", "XLSX", "MP3", "PDF", "EXE", "PY", "XLSX", "DOCX", "JPG", "PPTX"]
def get_extensions(extensions):
extensionlist = []
for item in extensions:
extension = item.lower()
for dictionary in extensionlist:
if dictionary["Extension"] == extension:
dictionary["Count"] += 1
break
else:
extensionlist.append({"Extension": extension, "Count": 1})
break
return extensionlist
test = get_extensions(extensions)
print(test)