将JSON加载到multiprocessing.managers.DictProxy对象中

时间:2018-04-12 19:52:00

标签: python json dictionary multiprocessing

我正在尝试将JSON对象加载到DictProxy对象中,但我没有看到" easy"办法。我可以很容易地将JSON加载到字典中,但是如果我尝试将此dict复制到DictProxy中,它将保持为dict(这与我正在进行的方式有关)。我可以创建一个空的DictProxy,然后构建一个循环遍历dict的函数并填充DictProxy,但我觉得这应该是不必要的。我也无法在DictProxy上找到很多文档,因此我不确定它与dict共享(或不共享)的功能。有没有一种干净的方法可以做到这一点,或者我应该构建循环遍历dict的函数并构建DictProxy

代码:

import multiprocessing
import json

def main():
    with open(r"c:\path\to\my.json") as js:
        my_dict = json.load(js)    
    print type(my_dict) # <type 'dict'>

    manager = multiprocessing.Manager()
    my_dict_proxy = manager.dict()
    print type(my_dict_proxy) # <class 'multiprocessing.managers.DictProxy'>

    my_dict_proxy = my_dict
    print type(my_dict_proxy) # <type 'dict'>

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:3)

DictProxy提供了update()方法。你应该能够做到这一点:

manager = multiprocessing.Manager()
my_dict_proxy = manager.dict()
my_dict_proxy.update(my_dict)