[Django]-Removing quotes from keys of dicts when rendering to template

3πŸ‘

βœ…

One approach you could use is overriding the __repr__ method of dict class or subclassing it and changing the method there. I have a the latter solution below.

class MyDict(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:{1}, ".format(key, self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s

MyDict({'a': 1, 'b': 2})
{a:1, b:2}

1πŸ‘

I found Stepan’s answer to be accurate and useful. It was useful in my case to also apply the rendering recursively, and to keep quotes on string elements. This extended version may also be useful to others:

class DictWithoutQuotedKeys(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:".format(key)
            if isinstance(self[key], basestring):
                # String values still get quoted
                s += "\"{0}\", ".format(self[key])
            elif isinstance(self[key], dict):
                # Apply formatting recursively
                s += "{0}, ".format(DictWithoutQuotedKeys(self[key]))
            else:
                s += "{0}, ".format(self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s
πŸ‘€John Walthour

1πŸ‘

Tweaked the code to deal with nested list and dictinory.
Code :

class DictWithoutQuotedKeys(dict):
def __repr__(self):
   # print(self)
    s = "{"
    
    for key in self:
        s += "{0}:".format(key)
        if isinstance(self[key], dict):
            # Apply formatting recursively
            s += "{0}, ".format(DictWithoutQuotedKeys(self[key]))
        elif isinstance(self[key], list):
            s +="["
            for l in self[key]:
                if isinstance(l, dict):
                    s += "{0}, ".format(DictWithoutQuotedKeys(l))
                else:
                    #print(l)
                    if isinstance(l, int):
                        s += "{0}, ".format(l)
                    else:
                        s += "'{0}', ".format(l)
            if len(s) > 1:
                s = s[0: -2]
            s += "], "
        else:
            if isinstance(self[key], int):
                s += "{0}, ".format(self[key])
            else:
                s += "\'{0}\', ".format(self[key])
            # Quote all the values
            #s += "\'{0}\', ".format(self[key])
    
    if len(s) > 1:
        s = s[0: -2]
    s += "}"
    return s

Input :

data = {'a':["1", "3", 4], 'b':[{'check1':9, 'check2':"kkk"}], 'c': {'d':2 , 'e': 3}, 'f':'dd', 't':2}

Output :

{a:['1', '3', 4], b:[{check1:9, check2:'kkk'}], c:{d:2, e:3}, f:'dd', t:2}

0πŸ‘

I found John’s solution useful, Tweaked his code a bit to suit my case. To Quote all the Values in dict and keys without Quotes in Dict

{
  "variant": {
    "id": 808950810,
    "option1": "Not Pink",
    "price": "99.00"
  }
}

To

{variant:{id:'32036302848074', compare_at_price:'39.83'}}
class DictWithoutQuotedKeys(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:".format(key)
            # if isinstance(self[key], str):
            #     # String values still get quoted
            #     s += "\"{0}\", ".format(self[key])
            # if isinstance(self[key], int):
            #     # String values still get quoted
            #     s += "\'{0}\', ".format(self[key])

            if isinstance(self[key], dict):
                # Apply formatting recursively
                s += "{0}, ".format(DictWithoutQuotedKeys(self[key]))
            else:
                # Quote all the values
                s += "\'{0}\', ".format(self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s

Leave a comment