How to generate a dictionary dynamically from a list in python?

Question:

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)
Asked By: Manas S. Roy

||

Answers:

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

Answered By: azro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.