Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将子目录移动到父目录?_Python_Python 3.x - Fatal编程技术网

Python 如何将子目录移动到父目录?

Python 如何将子目录移动到父目录?,python,python-3.x,Python,Python 3.x,我有一个孩子,像这样: { "bookname" : "Harry Potter", "book_details" : { "amount" : 12, "price" : 1000, } } d = { "bookname" : "Harry Potter", "book_details" : { "amount" : 12, "price" : 1000, } } result

我有一个孩子,像这样:

{
   "bookname" : "Harry Potter",
   "book_details" : {
         "amount" : 12,
         "price" : 1000,
   } 
}
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)
我想把这句话改为:

{
  "bookname" : "Harry Potter",
  "book_details_amount" :12,
  "book_details_price": 1000
}

对于您的特定dict,您可以将
book\u details
dict移动到父级,如下所示:

{
   "bookname" : "Harry Potter",
   "book_details" : {
         "amount" : 12,
         "price" : 1000,
   } 
}
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)
输出:

{'bookname': 'Harry Potter', 'book_details_amount': 12, 'book_details_price': 1000}

顺便说一句,“child”并不是真正正确的术语,它有点误导。不管怎样,你试过什么吗?这似乎是一个相当直接的转变。这是否回答了你的问题@andreis11之前被标记为重复的。我认为这些递归解决方案对于OP的要求来说太复杂了。