Home > Net >  Converting dictionary to string and Removing quotes of keys in python
Converting dictionary to string and Removing quotes of keys in python

Time:03-11

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

CodePudding user response:

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)
  • Related