Home > OS >  Converting all dict values to str
Converting all dict values to str

Time:10-16

I have a class method to convert dictionary values to str in preparation for adding it as post data to formdata, however, some values are not converting from int to str for example:

jsonData={
   "LanguageId":1,
   "ClientTypeId":2,
   "BrandId":3,
   "JurisdictionId":1,
   "ClientIntegratorId":1,
   "ExternalIds":[10372246,10372249,10372236,10372239,10372234,10372235,10372231,10372233,10377244,10377245,10377254,10377247,10377251,10377248,10377249,10377246
   ],
   "MarketCName":"win-draw-win",
   "ScoreboardRequest":{
      "ScoreboardType":3,
      "IncidentRequest":{}
   },
   "BrowserId":2,
   "OsId":4,
   "ApplicationVersion":"",
   "BrowserVersion":"15.4",
   "OsVersion":"10.15.7",
   "SessionId":'null',
   "TerritoryId":227,
   "CorrelationId":"71a5a843-a9cd-4152-9ef5-cede7ee59e33",
   "VisitId":"b0d95dbe-fc0c-482a-a45c-1e300c8682b9",
   "ViewName":"sports",
   "JourneyId":"77057d08-5dff-4da4-afd7-087b97024194"
}

Here is the class:

class StringDict(dict):
    def __init__(self):
        dict.__init__(self)
        
    def __getitem__(self, y):
        value_to_string = str(dict.__getitem__(self, y))
        return value_to_string
    
    def get(self, y):
        if isinstance(dict.get(self, y), list):
            value_to_string = [str(x) for x in dict.get(self, y)]
            
        elif isinstance(dict.get(self, y), dict):
            value_to_string = {}
            for keys, values in dict.get(self, y).items():
                if isinstance(values, dict):
                    values_to_string[keys] = values
                values_to_string[keys] = str(values)
                
        elif isinstance(dict.get(self, y), int) or isinstance(dict.get(self, y), float):
            value_to_string = str(dict.get(self, y))
        else:
            value_to_string = str(dict.get(self, y))
        return value_to_string

exampleDict = StringDict()

The test:

for key, values in jsonData.items():
    exampleDict[key] = values
[type(x) for x in {**exampleDict}.values()]

[int,
 int,
 int,
 int,
 int,
 list,
 str,
 dict,
 int,
 int,
 str,
 str,
 str,
 str,
 int,
 str,
 str,
 str,
 str]

I should only have either list, dict, str. Whereby all values inside the list are str and the same goes for the dict.

Expected output:

[str,
 str,
 str,
 str,
 str,
 list,
 str,
 dict,
 str,
 str,
 str,
 str,
 str,
 str,
 str,
 str,
 str,
 str,
 str]

All values in list and dict should also be str.

CodePudding user response:

You need to add an __iter__ method for values() to call your __getitem__:

def __iter__(self):
    return dict.__iter__()

This then prints:

[<class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>]

CodePudding user response:

You can try simple recursion to convert your dict:

def convert(o):
    if isinstance(o, dict):
        return {
            k: convert(v) if isinstance(v, (list, dict)) else str(v)
            for k, v in o.items()
        }
    elif isinstance(o, list):
        return [
            convert(v) if isinstance(v, (list, dict)) else str(v) for v in o
        ]


print(convert(jsonData))

Prints:

{
    "LanguageId": "1",
    "ClientTypeId": "2",
    "BrandId": "3",
    "JurisdictionId": "1",
    "ClientIntegratorId": "1",
    "ExternalIds": [
        "10372246",
        "10372249",
        "10372236",
        "10372239",
        "10372234",
        "10372235",
        "10372231",
        "10372233",
        "10377244",
        "10377245",
        "10377254",
        "10377247",
        "10377251",
        "10377248",
        "10377249",
        "10377246",
    ],
    "MarketCName": "win-draw-win",
    "ScoreboardRequest": {"ScoreboardType": "3", "IncidentRequest": {}},
    "BrowserId": "2",
    "OsId": "4",
    "ApplicationVersion": "",
    "BrowserVersion": "15.4",
    "OsVersion": "10.15.7",
    "SessionId": "null",
    "TerritoryId": "227",
    "CorrelationId": "71a5a843-a9cd-4152-9ef5-cede7ee59e33",
    "VisitId": "b0d95dbe-fc0c-482a-a45c-1e300c8682b9",
    "ViewName": "sports",
    "JourneyId": "77057d08-5dff-4da4-afd7-087b97024194",
}
  • Related