Kuk1a
Kuk1a

Reputation: 349

convert all the values in a dictionary to strings

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"])

Upvotes: 4

Views: 19732

Answers (6)

privod
privod

Reputation: 278

Maybe 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)

Upvotes: 7

Enrique
Enrique

Reputation: 1

With list comprehension :

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

Upvotes: 0

edusanketdk
edusanketdk

Reputation: 602

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']}")

Upvotes: 1

FloLie
FloLie

Reputation: 1840

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

Upvotes: 3

Ludal
Ludal

Reputation: 120

Why not:

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

Upvotes: 0

Vivs
Vivs

Reputation: 475

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)

Upvotes: 1

Related Questions