Reputation: 275
I have a JSON file having key value pairs. Currently I'm using python built in Replace() function to replace spaces with underscore but it also replace spaces with underscore in values.I only want to replace spaces from Keys, Values should remain the same. This is the python function I'm using
string=string.replace(" ","_")
Upvotes: 1
Views: 2478
Reputation: 44283
The assumption I am working under is that you first convert the Json string to a dictionary. Then:
The most pythonic (idiomatic, clearest and efficient) way to do this is with a dictionary comprehension:
d = {"key 1": "Value 1", "key 2": "value 2"}
new_d = {k.replace(" ", "_"): v for k, v in d.items()}
print(new_d)
Prints:
{'key_1': 'Value 1', 'key_2': 'value 2'}
d.items()
iterates all the key/value pairs of the dictionary as variables k
and v
in the above code and after the spaces are replaced with underscores in k
, a new dictionary is created from these k
and v
pairs.
You can then convert the dictionary back to a Json string.
Upvotes: 5
Reputation: 2344
You cannot change the keys. What you can do is add the modified key, value pair and then remove the old one.
Let's say you have a dictionary like below:
{'x c': 'z c'}
You can write following script to replace whitespaces in keys:
x = {"x c":"z c"}
for key,value in x.iteritems():
new_key = key.replace(" ","_")
del x[key] # Deleting Previous Key
x[new_key] = value # Adding Modified key
Output:
{'x_c': 'z c'}
Hope this helps you out!!!
Upvotes: 1