简体   繁体   中英

Python dictionary not adding subsequent keys after the first

Fairly new to Python and I can not figure this out. 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}

Your __str__ implementation returns on the first iteration of the for-loop:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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