Reputation: 5
I have a JSON file that has been generated from transfer learning that calculates the probability, following:
{"str.++,C_1": {
"C_1": 1
},
"Var,str.replace": {
"C_2": 1
},
"str.replace,_": {
"str.replace": 0.8571428571428571,
"Var": 0.14285714285714285
}}
that need to be changed to like following, changing the value to keys as context, rule, and probability:
[{
"context": "Var,str.replace",
"rule": "C_2",
"prob": 1
},
{"context":"str.++,C_1",
"rule":"C_1",
"prob": 1
},
{"context":"str.replace,_",
"rule":"str.replace, var"
"prob": 0.8571428571428571, 0.14285714285714285
}]
I tried dumps from the original python code but it just dumps value into key.
Upvotes: 0
Views: 126
Reputation: 59174
This can easily be done using a list comprehension:
>>> d = {'str.++,C_1': {'C_1': 1}, 'Var,str.replace': {'C_2': 1}, 'str.replace,_': {'str.replace': 0.8571428571428571, 'Var': 0.14285714285714285}}
>>> [{"context": k, "rule": list(v.keys()), "prob": list(v.values())} for k, v in d.items()]
output:
[{'context': 'str.++,C_1', 'rule': ['C_1'], 'prob': [1]},
{'context': 'Var,str.replace', 'rule': ['C_2'], 'prob': [1]},
{'context': 'str.replace,_', 'rule': ['str.replace', 'Var'], 'prob': [0.8571428571428571, 0.14285714285714285]}]
Note that "prob": 0.8571428571428571, 0.14285714285714285
is not a valid JSON value in your expected output. The above code correctly encodes that part as a list/array.
Upvotes: 1