有什么方法可以使用 Python 2.7将 JSON 代码加载到递归中defaultdict以避免?KeyError
例如:
from __future__ import print_function
from collections import defaultdict
import json
S = '{"a": [{"b": "TEST1", "p": "TEST2"}, {"b": "TEST3", "p": "TEST4"}]}'
d = json.loads(S)
nd = lambda: defaultdict(nd)
ni = nd()
print('1: ', ni['a'][0]['b'])
ni.update(d)
print('2: ', ni['a'][0]['b'])
print('3: ', ni['a'][1]['p'])
print('4: ', ni['a'][1]['c'])
Run Code Online (Sandbox Code Playgroud)
结果
from __future__ import print_function
from collections import defaultdict
import json
S = '{"a": [{"b": "TEST1", "p": "TEST2"}, {"b": "TEST3", "p": "TEST4"}]}'
d = json.loads(S)
nd = …Run Code Online (Sandbox Code Playgroud)