convert all the values in a dictionary to strings

Viewed 5233

Say I have a mixed list of dictionaries with strings and integers as values and I want to convert the integers to strings, how should one do that without going all over the place and converting them one by one considering that the list is fluid, long and might also change some of the existing values to integers.

Example:

list = [{'a':'p', 'b':2, 'c':'k'},
        {'a':'e', 'b':'f', 'c':5}]

Now if I'll try and print the values of the list with a string it will give me an error as follows.

Example:

for x in list:
    print('the values of b are: '+x['b'])

Output:

TypeError: can only concatenate str (not "int") to str

Process finished with exit code 1

Any help is appreciated, Thanks!

SOLUTION

list = [{'a':'p', 'b':2, 'c':'k'},
        {'a':'e', 'b':'f', 'c':5}]

for dicts in list:
    for keys in dicts:
        dicts[keys] = str(dicts[keys])
print('the values of b are: '+ dicts["b"])
6 Answers

The other solutions all do a one time translation to String, however, that does not help when you can't control if the values are changed back subsequently.

I suggest to subclass dict as such:

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):
        value_to_string = str(dict.get(self, y))
        return value_to_string
    
    

exampleDict = StringDict()

exampleDict["no_string"] = 123

print(exampleDict["no_string"])
123
print(type(exampleDict["no_string"]))
<class 'str'>

This way, the value type is not changed, but upon access it will be converted to String on the fly, guaranteeing it returns a String

If you want to convert the dictionary values to strings and then print:

list = [{'a':'p', 'b':2, 'c':'k'}, {'a':'e', 'b':'f', 'c':5}]
list = [{str(j): str(i) for i, j in enumerate(d)} for d in list]

for x in list:
    print("the values of b is: " + x['b'])

If you just want to print them without changing:

for x in list:
    print(f"the values of b is: {x['b']}")

Try this

list = [{'a':'p', 'b':2, 'c':'k'},
        {'a':'e', 'b':'f', 'c':5}]

for dicts in list:
    for keys in dicts:
        dicts[keys] = str(dicts[keys])
print(list)

Why not:

print(f"The value of b is: {x['b']}")

Maby this:

list = [
   {'a':'p', 'b':2, 'c':'k'},
   {'a':'e', 'b':'f', 'c':5}
]
list = [{key: str(val) for key, val in dict.items()} for dict in list]
print(list)

With list comprehension :

list = [{key: str(dict[key]) for key in dict.keys()} for dict in list]
Related