Dejwi
Dejwi

Reputation: 4487

Python dictionary with objects into dictionary with strings

I've got dictionary with objects values and string keys:

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

And I'd like to convert it into:

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

Where str(object_1) is a string representation of object_1. What is the simplest and the most pythonic way of performing this transformation?

Upvotes: 3

Views: 220

Answers (6)

CoffeeRain
CoffeeRain

Reputation: 4522

The following Python for loop should solve your problem.

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

Upvotes: 1

Infinite_Loop
Infinite_Loop

Reputation: 380

I had to do something similar to your question, but I think my solution is a bit long.

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

hope this helps

Upvotes: 0

mankand007
mankand007

Reputation: 992

You can also use this to achieve it without using any inbuilt methods for dictionary:

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

Upvotes: 1

Óscar López
Óscar López

Reputation: 236124

Using dictionary comprehensions:

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

The above will work in Python 2.7+, and it will generate the new dictionary using a generator. For Python 3, this will work similarly:

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

Upvotes: 2

eumiro
eumiro

Reputation: 213035

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 complicated 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()}

Upvotes: 10

Kenan Banks
Kenan Banks

Reputation: 212108

What eurimo said, or if you'd prefer not to make a copy:

for k in d:
   d[k] = str(d[k])

Upvotes: 3

Related Questions