Riverman
Riverman

Reputation: 523

Get key values from a nested dictionary

I'm trying to write a very simple, yet modular script to rename files.

I would like to process the contents of a JSON file, however, I'm stuck at returning all the sub-values of a key(object?) not just one.

My test code looks like this so far:

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)

Contents of the imported 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"
    }
  }
}

The Book1, Book2, Bookx keys in the JSON file would be hard-coded in the script, as I'd like to rename different files based on the user input using branching statements. For example, if the user picks Book1, then rename each old_name value to new_name, but don't mind the number of occurrences of "sections". (The number of sections (Book1_section1) could change overtime, therefore, I want my script to iterate on each occurrence of sections.)

My problem is that, I don't know how to ignore the Book1_section1, Book1_section2, etc... keys in my JSON and only parse their content. With

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

I can get the value I want but I don't know how to get all the values.

Upvotes: 0

Views: 1250

Answers (1)

Argus Malware
Argus Malware

Reputation: 787

you should try using nested traversal of dict

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

Upvotes: 1

Related Questions