Python dictionary with objects in a dictionary with strings

I have a dictionary with object values ​​and string keys:

dict{
'key1': object_1
'key2': object_2
}

And I would like to convert it to:

dict{
'key1': str(object_1)
'key2': str(object_2)
}

Where str (object_1) is the string representation of object_1. What is the easiest and most pythonic way to do this conversion?

+3
source share
6 answers
dict((k, str(v)) for k, v in d.iteritems())

or in Python2.7 +:

{k: str(v) for k, v in d.items()}

For more complex dicts (with tuples of objects as values):

dict((k, tuple(str(x) for x in v)) for k, v in d.iteritems())

{k: tuple(str(x) for x in v) for k, v in d.items()}
+10
source

What eurimo said or if you do not want to make a copy:

for k in d:
   d[k] = str(d[k])
+3
source

:

{ k : str(v) for k, v in d.iteritems() }

Python 2.7+, . Python 3 :

{ k : str(v) for k, v in d.items() }
+2

Python for .

for item in d.keys():
   d[item]=str(d[item])
+1

:

x = {z: str (x [z]) z x}

+1

- , , .

new_dict=dict([(item[0],str(item[1])) for item in d.items()])

hope this helps

0
source

All Articles