New course! Every coder should learn Generative AI!
Try a free lesson+ 1
Create json and append dict to list?
I am newbie and want to achieve the following: http://www.objgen.com/json/models/ykcJ { "background": { "elements": [ { "id": "1", "filename": "Blue.jpg" }, { "id": "2", "filename": "Red.jpg" }, { "id": "3", "filename": "Green.jpg" }, { "id": "4", "filename": "Brown.jpg" } ] } My code: def getElement(dir): counter = 0 for path in pathlib.Path(dir).iterdir(): if path.is_file(): value = { "id": counter += 1, "name": cleanName(path.name), "filename": path.name } elements = [] elements.append(value) print('element: ',elements) return elements
2 Answers
+ 1
Try to move this line
elements = []
Below this line
counter = 0
It seems you are recreating <elements> inside the loop.
+ 1
Ipang 🤦 stupidest mistake 😅
Thank You