Converting dictionary to string and Removing quotes of keys in python

Viewed 104

Note: recommendations from similar questions didn't work

I have a dictionary in python looks like this:

print(dic_test)
   {'name':'Tom','school':'NX'}

type(dic_test)
    <class 'dict'>

How can I get a string looks like this:

print(str_test)
   {name:"Tom",school:"NX"}

type(str_test)
    <class 'str'>

Converting dictionary to string and Removing quotes of keys in python

2 Answers

You can iterate over the keys and values of the dictionary and add them to the string in the format you want

str_test = "{"
for key, val in dic_test.items():
    str_test += key + ':"' + val + '",'

# deletes last trailing comma
str_test = str_test[:-1]

str_test += "}"
print(str_test)

Thanks, it works:

str_test = "{"
for key,value in dic_test.items():
    str_test += key + ':"' + str(value) + '",'
str_test = str_test[:-1] + "}"
Related