简体   繁体   English

Python字典在第一个之后不添加后续键

[英]Python dictionary not adding subsequent keys after the first

Fairly new to Python and I can not figure this out. 相当新的Python,我无法弄清楚这一点。 I go to add a key to a dictionary and it adds it fine. 我去添加一个字典的密钥,它添加它很好。 I can even update that same key with a new value, however when I go to add a second key to the dictionary, it does not add the second key value pair. 我甚至可以使用新值更新相同的密钥,但是当我向字典添加第二个密钥时,它不会添加第二个密钥值对。

class CountedSet:
    def __init__(self):
        self.data = {}
    def __iadd__(self,other):
        if isinstance(other,int):
            self.data[other] = self.data.get(other, 0) + 1
            return self
        elif isinstance(other,CountedSet):
            #TODO::iterate through second countedSet and update self
            return self
    def __add__(self,obj):
        for key, value in obj.data.items():
            if len(self.data) == 0:
                self.data[key] = value
            elif self.data[key]:
                self.data[key] = self.data[key] + value
            else:
                self.data[key] = value
        return self
    def __getitem__(self,item):
        if item in self.data:
            return self.data.get(item)
        else:
            return None
    def __str__(self):
        for key, value in self.data.items():
            return("{%s,%s}" % (key,value))
a = CountedSet()
a += 17
a += 4
print(a)

This simply outputs {17,1} when I would expect to see {17,1} {4,1} 当我希望看到{17,1} {4,1}时,这只会输出{17,1}

Your __str__ implementation returns on the first iteration of the for-loop: 你的__str__实现在for循环的第一次迭代时返回:

def __str__(self):
    for key, value in self.data.items():
        return("{%s,%s}" % (key,value)) # here

Maybe you want something like: 也许你想要的东西:

def __str__(self):
    return " ".join([{"{%s,%s}" % (k,v) for k, v in self.data.items()])

Or, without the comprehension: 或者,没有理解:

def __str__(self):
    items = []
    for key, value in self.data.items():
        items.append("{%s,%s}" % (key,value))
    return ' '.join(items)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM