繁体   English   中英

从嵌套字典中获取键值

[英]Get key values from a nested dictionary

我正在尝试编写一个非常简单的模块化脚本来重命名文件。

我想处理JSON文件的内容,但是,我坚持返回键(对象?)的所有子值,而不仅仅是返回一个。

到目前为止,我的测试代码如下所示:

import json

DB_dict = json.load(open("../source_code/db3.json", encoding='utf-8-sig'))
old_names_of_Book1 = DB_dict["Book1"]["Book1_section1"]["old_name"]
print(old_names_of_Book1)
print("________________________")

for key, values in DB_dict.items():
    print(key)
    print(values)

导入的db3.json的内容:

{
  "Book1": {
    "Book1_section1": {
      "old_name": "Adventures of X1",
      "new_name": "Adventures of Y1"
    },
    "Book1_section2": {
      "old_name": "Adventures of X2",
      "new_name": "Adventures of Y2"
    },
    "Book1_section3": {
      "old_name": "Adventures of X3",
      "new_name": "Adventures of Y3"
    },
    "Book1_section4": {
      "old_name": "Adventures of X4",
      "new_name": "Adventures of Y4"
    }
  },
  "Book2": {
    "Book2_section1": {
      "old_name": "Adventures of X1",
      "new_name": "Adventures of Y1"
    },
    "Book2_section2": {
      "old_name": "Adventures of X2",
      "new_name": "Adventures of Y2"
    },
    "Book2_section3": {
      "old_name": "Adventures of X3",
      "new_name": "Adventures of Y3"
    },
    "Book2_section4": {
      "old_name": "Adventures of X4",
      "new_name": "Adventures of Y4"
    }
  }
}

JSON文件中的Book1,Book2,Book x键将在脚本中进行硬编码,因为我想使用分支语句根据用户输入来重命名不同的文件。 例如,如果用户选择Book1,然后将每个old_name值重命名为new_name ,但不必new_name “ sections”的出现次数。 (部分的数量( Book1_section1 )可以随时间变化,因此,我希望我的脚本在每次出现部分时都进行迭代。)

我的问题是,我不知道如何忽略JSON中的Book1_section1Book1_section2等...键,仅解析其内容。

print(DB_dict["Book1"]["Book1_section1"]["old_name"])

我可以获得想要的值,但我不知道如何获取所有值。

你应该尝试使用字典的嵌套遍历

for m,n in DB_dict.items():
    if m == str("Book1"):
        for x,y in n.items():
            print(y["old_name"])   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM