Reputation: 62596
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(',')
Upvotes: 0
Views: 197
Reputation: 1017
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'
Upvotes: 0
Reputation: 250921
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'"
Upvotes: 4
Reputation: 8786
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)
Upvotes: 2