'Converting dictionary to string and Removing quotes of keys in python

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



Solution 1:[1]

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)

Solution 2:[2]

Thanks, it works:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 shanwli89