-2

I have a dict with child like this:

{
   "bookname" : "Harry Potter",
   "book_details" : {
         "amount" : 12,
         "price" : 1000,
   } 
}

I want to covert dict to below:

{
  "bookname" : "Harry Potter",
  "book_details_amount" :12,
  "book_details_price": 1000
}
martineau
  • 119,623
  • 25
  • 170
  • 301
devnext
  • 872
  • 1
  • 10
  • 25
  • 2
    As an aside, "child" is not really the correct terminology, it's a bit misleading. Anyway, have you tried anything at all? This seems like a rather straight-forward transformation. – juanpa.arrivillaga Apr 19 '20 at 23:40
  • 2
    Does this answer your question? [Flatten nested dictionaries, compressing keys](https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys) – andreis11 Apr 20 '20 at 03:06
  • @andreis11 Was previously marked as duplicate with that. I think those recursive solutions are too complicated for the OP's requirement. – RoadRunner Apr 20 '20 at 07:10

1 Answers1

2

For your specific dict, you can move book_details dict to the parent level like this:

d = {
   "bookname" : "Harry Potter",
   "book_details" : {
         "amount" : 12,
         "price" : 1000,
   } 
}

result = {"bookname": d["bookname"]}

for k, v in d["book_details"].items():
    result[f"book_details_{k}"] = v

print(result)

Output:

{'bookname': 'Harry Potter', 'book_details_amount': 12, 'book_details_price': 1000}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75