简体   繁体   中英

How to extract a key value pair from a nested dictionary and output it in json

I am extracting part of a dictionary with

with open(output_filename, "w") as outfile:
    json.dump(data['metadata'], outfile)

So that I get the value of 'metadata' and none of the key value pairs before. How do I modify it so I also get the key itself ('metadata') to appear in the output before the value? I tried this

for key in my_dict.keys():
   if key is "metadata":
       val = my_dict[key]

and then using json.dump(val, outfile) but that created an error global name val is not defined (I defined it as a global variable earlier to try to fix an earlier error message.) I can't use just "data" itself because there is a key value pair in data that I want to exclude.

with open(output_filename, "w") as outfile:
    json.dump({'metadata': data['metadata']} , outfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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