Home > OS >  How to generate a dictionary dynamically from a list in python?
How to generate a dictionary dynamically from a list in python?

Time:08-29

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)

CodePudding user response:

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

  • Related