Reputation: 531
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.
Upvotes: 0
Views: 270
Reputation: 403
with open(output_filename, "w") as outfile:
json.dump({'metadata': data['metadata']} , outfile)
Upvotes: 2