0

I want to run a script which grabs all the titles of the files in a folder and collects them in a dictionary. I want the output structured like this:

{
    1: {"title": "one"},
    2: {"title": "two"},
    ...
}

I have tried the following, but how to add the "title"-part and make the dictionary dynamically?

from os import walk

mypath = '/Volumes/yahiaAmin-1'

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

courseData = {}

   
for index, x in enumerate(filenames):
    # print(index, x)
    # courseData[index]["title"].append(x)
    # courseData[index].["tlt"].append(x)
    courseData.setdefault(index).append(x)

print(courseData)
1
  • are "one", "two" the titles ? Commented Aug 28, 2022 at 10:01

1 Answer 1

1

Assign the value dict directly to the index

courseData = {}
filenames = ["one", "two"]

for index, x in enumerate(filenames, 1):
    courseData[index] = {"title": x}

print(courseData)
# {1: {'title': 'one'}, 2: {'title': 'two'}}

Not that using a dict where the key is an incremental int is generally useless, as a list will do the same

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.