python:在东京橱柜商店中递增值

时间:2011-12-03 19:24:56

标签: python tokyo-cabinet

我使用tcdb来存放一个大的键值存储。键是表示用户ID的字符串,值是表单的格式

{'coord':0,'node':0,'way':0,'relation':0}

商店被遍历一个数据文件,该数据文件包含coord,node,way和relation对象,每个对象都链接到特定用户。这是我增加字段的代码:

def increment(self,uid,typ):
    uid = str(uid)
    type = str(typ)
    try:
        self.cache[uid][typ] += 1
    except KeyError:
        try:
            self.cache[uid][typ] = 1
        except KeyError:
            try:
                print 'creating record for %s' % uid
                self.cache[uid] = {'coord':0,'node':0,'way':0,'relation':0}
            except KeyError:
                print 'something\'s messed up'

这不起作用。我最终得到一个具有全零值的表:

def result(self):
    print 'cache is now %i records' % len(self.cache)
    for key in self.cache:
        print key + ': ' + str(self.cache[key])

的产率:

...
4951: {'node': 0, 'coord': 0, 'relation': 0, 'way': 0}
409553: {'node': 0, 'coord': 0, 'relation': 0, 'way': 0}
92274: {'node': 0, 'coord': 0, 'relation': 0, 'way': 0}
259040: {'node': 0, 'coord': 0, 'relation': 0, 'way': 0}
...

为什么?

永远不会调用最后一个异常。

编辑第一个try块中的此代码:

        tempdict = self.cache[uid]
        tempdict[typ] = tempdict.get(typ,0) + 1
        self.cache[uid] = tempdict

而不是原来的

        self.cache[uid][typ] += 1

有效,但看起来真的很丑。

1 个答案:

答案 0 :(得分:2)

这一行之后:

self.cache[uid] = {'coord':0,'node':0,'way':0,'relation':0}

添加:

self.cache[uid][type] = 1

另外,请不要将type用作变量名,因为它会隐藏同名的内置内容。

相关问题