Home > Software engineering >  How to print key-value as string using __str__ method - dictionary
How to print key-value as string using __str__ method - dictionary

Time:06-04

I am stuck on using str method for print out what I want. I want to print out this type of format: { 'key': value, 'key': value, 'key': value, 'key': value, 'key': value} by using str method.

class DataM(object):
   def __init__(self):
       self.a = {}
    
   def insert(self, key, val):
        if not key in self.a.keys():
             self.a[key] = val
       else:
          print("The key is already exist")

  def delete(self, key):
      try:
          del self.a[key]
      except:
          raise ValueError("Cannot remove the key ")

  def get(self, key):
     try:
         return self.a[key]
     except:
         return None
    
  def contain(self, key):
      return key in self.a 

  def __str__(self):
     result = ''
     for key, value in self.a.items():
         result = result str(key)   " :"   str(value)   ','
     return "{"  result[:-1]  "}"
           
    

dataM = DataM()
dataM.insert("a", 200)
dataM.insert("c", 400)
dataM.insert("e", 1)
dataM.insert("g", 23)
dataM.insert("h", 74)
print(dataM)

for example, if i print(dataM): the result should be like this: {' a ' : 20, ' c ' : 400, ' e ' : 1, ' g ' : 23, ' h ' : 74} by using __str__method.

If you guys can give any advice or idea, it would be appreciate it a lot.

CodePudding user response:

It sounds like what you want is the string representation of the self.a dictionary, so just return that directly rather than trying to reimplement dict.__str__ yourself:

  def __str__(self):
     return str(self.a)

The same applies for some of your other methods, e.g.:

  def get(self, key):
     return self.a.get(key)

I assume you're wrapping the dictionary for some specific educational purpose, but in "real life", you would most likely want to skip all this and just use a regular dictionary.

  • Related