尝试从嵌套的Manager.dict访问密钥值时的KeyError [英] KeyError when attempting to access a key value from a nested Manager.dict

查看:457
本文介绍了尝试从嵌套的Manager.dict访问密钥值时的KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些多处理代码,我想在进程之间共享一个嵌套字典。字典从来没有被进程修改;只需阅读。



在最简单的形式中,有问题的代码如下:

 

class MyClass(object):

def __init __(self):
self.manager = Manager()
self.delays = self.manager.dict({})

def foo(self,types,keys):
类型的类型:
self.delays [type] = self.manager.dict({})

键中的键:
self.delays [type] [key] = 0

print(延迟是+ str(self.delays [type] [key]))

我在print语句中得到一个 KeyError ,它表示我使用的键不存在。我不知道为什么会发生这种情况,因为我只是把钥匙插入了dict。当我把它改成一个常规的dict,问题就会消失。

解决方案

根据这个answer 相关问题,您可以使用附加一个dict的 Manager.list 然后使用引用to the dict:

 从多进程导入管理器
class MyClass(object):

def __init __(self):
self.manager = Manager()
self.l = self.manager.list()
self.l.append({})
self .delays = self.l [0]

def foo(self,types,keys):
类型中的类型:
self.delays [type] = self.manager .dict()
键中的键:
self.delays [type] .setdefault(key,0)
print(延迟是{}format(self.delays [ type] [key]))


I have some multiprocessing code where I'd like to share a nested dictionary among processes. The dictionary is never modified by the processes; just read.

In the simplest form, the problematic code is as follows:

from multiprocessing import Manager

class MyClass(object):

    def __init__(self):
        self.manager = Manager()
        self.delays = self.manager.dict({})

    def foo(self, types, keys):
        for type in types:
            self.delays[type] = self.manager.dict({})

            for key in keys:
                self.delays[type][key] = 0

                print("The delay is " + str(self.delays[type][key]))

I get a KeyError at the print statement where it says that the key I'm using does not exist. I'm not sure why this is happening, since I just inserted the key into the dict. When I change this into a regular dict, the problem goes away.

解决方案

Based on this answer to a related question, you can use a Manager.list appending a dict, then use a reference to the dict:

from multiprocessing import Manager
class MyClass(object):

    def __init__(self):
        self.manager = Manager()
        self.l = self.manager.list()
        self.l.append({})
        self.delays = self.l[0]

    def foo(self, types, keys):
        for type in types:
            self.delays[type] = self.manager.dict()
            for key in keys:
                self.delays[type].setdefault(key, 0)
                print("The delay is {}".format(self.delays[type][key]))

这篇关于尝试从嵌套的Manager.dict访问密钥值时的KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆