众所周知,json
将 dict 的整数键转换为字符串:
import json
print json.dumps({1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]})
# {"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}
加载回来时恢复整数键最干净的方法是什么?
d = json.loads('{"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}')
print d
# {u'1': [2.5, 2.5, 2.5], u'2': [3, 3, 3, 3]}
我在想:
d = {int(k): d[k] for k in d}
但是有没有更简洁的方法来处理带有 JSON/Python 整数键的字典,而不需要事后进行键转换?
最佳答案
使用object_hook
定义自定义函数并执行操作:
import json
def keystoint(x):
return {int(k): v for k, v in x.items()}
j = json.dumps({1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]})
# {"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}
print(json.loads(j, object_hook=keystoint))
# {1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]}
来自 docs :
object_hook
is an optional function that will be called with the result of any object literal decoded (a dict). The return value ofobject_hook
will be used instead of the dict.
或者,您也可以使用
object_pairs_hook
来迭代对并保存 .items()
调用(感谢@chepner):
import json
def keystoint(x):
return {int(k): v for k, v in x}
j = json.dumps({1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]})
# {"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}
print(json.loads(j, object_pairs_hook=keystoint))
# {1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]}
来自文档:
object_pairs_hook
is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value ofobject_pairs_hook
will be used instead of the dict.
关于python - 读取 JSON 并将键转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53050408/