Add Python Dictionary Value and Output to String

Asked 2 years ago, Updated 2 years ago, 77 views

class HashMap:
    def __init__(self):
        self.vals = {}
    def insert(self, key, val):
        self.vals = {key:val}
    def __str__(self):
        result = ''
        for i in self.vals.items():
            result = result + str(i) + ','
        return '{' + result[:-1] + '}'

hashMap = HashMap()
hashMap.insert("grade", 1)
hashMap.insert("number", 60171234)
hashMap.insert("name", "Gildong Hong")
print(hashMap)

I'll run the code {"grade" : 1, "number" : 60171234, 'name' : 'Gildong Hong'} I want these results to be printed as a string, but I can't add dictionary values and the last output result is not as I thought How can I fix it? I'd appreciate your help

python class dictionary

2022-09-22 19:01

1 Answers

class HashMap:
    def __init__(self):
        self.vals = {}
    def insert(self, key, val):
        self.vals[key] = val

The biggest problem was to keep resetting from insert.

__str___ is a little wrong in the output format, but I'm sure you'll fix it well.


2022-09-22 19:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.