简体   繁体   中英

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

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] + "}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM