[英]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. 您可以将
str.join
与生成器表达式结合使用。 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 '{}'
. 如果您想使用引号引起来,而不管它们的类型如何,请将
{!r}
替换为'{}'
。 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: .join
用于通过字符将一个可迭代的项目连接在一起,因此您需要将这些项目附加到列表中,然后以逗号结尾将它们连接在一起,如下所示:
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() )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.