小编Vla*_*pov的帖子

如何将 dict 转换为递归 defaultdict 并加载 JSON?

有什么方法可以使用 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)

python recursion json python-2.7 defaultdict

2
推荐指数
1
解决办法
3969
查看次数

标签 统计

defaultdict ×1

json ×1

python ×1

python-2.7 ×1

recursion ×1