[英]convert dictionaries into string python
I am trying to convert dictionaries into string 我正在尝试将字典转换为字符串
for example: 例如:
a={3:4,5:6}
s='3 4, 5 6'
The way I am trying is 我正在尝试的方式是
s=''
i=0
for (k,v) in d.items():
s=s+str(k)+' '+str(v)
while i < len(s):
if s[i]==str(v) and s[i+1]==str(k):
s+=s+s[i]+','+s[i+1]
Here's a Pythonic way of doing that using a list comprehension : 这是使用列表理解的Pythonic方法:
s = ', '.join([str(x) + ' ' + str(a[x]) for x in a])
Output: 输出:
'3 4, 5 6'
Update: As Julien Spronck mentioned, the square brackets ( [
and ]
) are not necessary. 更新:正如Julien Spronck所说,方括号(
[
和]
)不是必需的。 Thus, the following has the same effect: 因此,以下具有相同的效果:
s = ', '.join(str(x) + ' ' + str(a[x]) for x in a)
You can write the list comprehension expression to get the list of key-value string, then join them on ,
as 您可以编写列表推导表达式来获取键值字符串列表,然后将它们连接起来
,
如
>>> d = {3:4,5:6}
>>> ', '.join('{} {}'.format(k, v) for k, v in d.items())
'3 4, 5 6'
OR, even using repr()
( Note: it is a hack, I consider .join()
approach more pythonic ): 或者,甚至使用
repr()
( 注意:它是一个hack,我认为.join()
接近pythonic ):
>>> repr(d)[1:-1].replace(':', '')
'3 4, 5 6'
I would use the following with a list comprehension: 我将使用以下列表理解:
', '.join([str(k) + ' ' + str(v) for k, v in a.items()])
To illustrate: 为了显示:
In [1]: a = {3:4, 5:6}
In [2]: s = ', '.join([str(k) + ' ' + str(v) for k, v in a.items()])
In [3]: s
Out[3]: '3 4, 5 6'
Of course the most pythonic solution is the one using the list comprehension (see @SumnerEvans and the rest) but just for the sake of having an alternative i will post this here: 当然,最pythonic解决方案是使用列表理解的解决方案(参见@SumnerEvans和其他),但只是为了有替代方案,我将在此处发布:
a = {3: 4, 5: 6}
v = str(a)
for rep in ['{', '}', ':']:
v = v.replace(rep, '')
print(v) # prints -> 3 4, 5 6
Everything can be converted into a string and the manipulated as one. 一切都可以转换成一个字符串,并作为一个操纵。 This is what is being done here.
这是在这里做的。 From
dict
to string
and then chained replace
methods. 从
dict
到string
然后链接replace
方法。
You can still have it like this 你仍然可以这样
s=''
i=0
a={3:4,5:6}
for (k,v) in a.items():
if i < len(a) and s == '':
s = s + str(k) + ' '+ str(v)
elif i < len(a) and s != '':
s += ", " + str(k) + ' '+ str(v)
i += 1
print(s)
This should give you 这应该给你
s='3 4, 5 6'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.