如何用预定义的键字符串python(2.x)嵌套字典?

2024-04-26 07:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,很抱歉,我无法实现这个问题的可用答案,我对python非常陌生,我只需要构建一个json,如下所示:

文件夹名称=城市名称

{
    "Berlin": {
        "files":[ "file1.pdf", "file2.pdf"]
    },
    "Budapest": {
        "files":[ "file1.pdf", "file2.pdf"]
    }
}

我几乎可以用这个做这个

rootdir = "D:\\scripttest\\pdf"
content = {}

for root, dirs, files in os.walk(rootdir):
    content[root.split('\\')[-1]] = files
print content

with open("D:\\scripttest\\pdfconf.json", 'w') as pdfConf:
    json.dump(content, pdfConf)

这是我的输出: {"Berlin": ["file1.pdf", "file2.pdf"], "Budapest": ["file1.pdf", "file2.pdf"]}

所以我需要将我的值导出为外部dict的值,并在dict中插入一个新值,但我感到困惑。 我很乐意得到任何帮助


1条回答
网友
1楼 · 发布于 2024-04-26 07:33:40

您需要使用"files"作为键显式创建dict

for root, dirs, files in os.walk(rootdir):
    city = os.path.basename(root)
    content[city] = {'files': files}

使用os.path模块来操作路径,而不是将它们视为原始字符串

相关问题 更多 >