[英]Combine a Ordereddict and default dict and dump it in a json file
I have two variable which holds a ordered dict and default dict respectively.我有两个变量分别保存有序字典和默认字典。 I want to combine those and form a valid json.
我想结合这些并形成一个有效的json。
a = OrderedDict([('cat', 80.0), ('dog', 119.07)])
b = defaultdict(<type 'dict'>, {'apple': {'solid': {'NZL': 5032000, 'SHM': 79196000}, 'water':
{'NZL': 1000, 'SHM': 6000}, 'grains': 232000}, 'mango': {'solid': {'ALP': 47283305}, 'water':
{}, 'grains': 330611}})
with open('data.json','w') as file:
json.dump(a, file, indent=5)
file.write('\n')
json.dump(b, file, indent=5)
I want the output as :我希望输出为:
[
{
"cat":80.0,
"dog":119.07
},
{
"apple":{
"solid":{
"NZL":5032000,
"SHM":79196000
},
"water":{
"NZL":1000,
"SHM":6000
},
"grains":232000
},
"mango":{
"solid":{
"ALP":47283305
},
"water":{
},
"grains":330611
}
}
]
Anyone help me out with this.任何人都可以帮我解决这个问题。
Both OrderedDict
and defaultdict
are already serializable, so you can just do this easily: OrderedDict
和defaultdict
都已经是可序列化的,所以你可以很容易地做到这一点:
with open("data.json", "w") as f:
json.dump([a, b], f, indent=4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.