[英]How to generate a dictionary dynamically from a list in python?
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:
我想要 output 的结构如下:
{
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)
Assign the value dict directly to the index将值 dict 直接分配给索引
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并不是说使用键是增量
int
的 dict 通常是没用的,因为列表也会这样做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.