简体   繁体   中英

How to convert a dict to string?

Assume I have a dict:

{
'a':'vala',
'b':'valb',
'c':'valc'
}

I want to convert this to a string:

"a='vala' , b='valb' c='valc'"

What is the best way to get there? I want to do something like:

mystring = ""
for key in testdict:
  mystring += "{}='{}'".format(key, testdict[key]).join(',')

You can use str.join with a generator expression for this. Note that a dictionary doesn't have any order, so the items will be arbitrarily ordered:

>>> dct = {'a':'vala', 'b':'valb'}
>>> ','.join('{}={!r}'.format(k, v) for k, v in dct.items())
"a='vala',b='valb'"

If you want quotes around the values regardless of their type then replace {!r} with '{}' . An example showing the difference:

>>> dct = {'a': 1, 'b': '2'}
>>> ','.join('{}={!r}'.format(k, v) for k, v in dct.items())
"a=1,b='2'"
>>> ','.join("{}='{}'".format(k, v) for k, v in dct.items())
"a='1',b='2'"

Close! .join is used to join together items in an iterable by a character, so you needed to append those items to a list, then join them together by a comma at the end like so:

testdict ={
'a':'vala',
'b':'valb'
}
mystring = []
for key in testdict:
  mystring.append("{}='{}'".format(key, testdict[key]))

print ','.join(mystring)

Well, just if you want to have a sorted result:

d={'a':'vala', 'b':'valb', 'c':'valc'}
st = ", ".join("{}='{}'".format(k, v) for k, v in sorted(d.items()))
print(st)

Result

a='vala', b='valb', c='valc'
" , ".join( "%s='%s'"%(key,val) for key,val in mydict.items() ) 

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