将字典转换为字符串python

Sil*_*hen 3 python string dictionary

我正在尝试将字典转换为字符串

例如:

a={3:4,5:6}
s='3 4, 5 6'
Run Code Online (Sandbox Code Playgroud)

我正在尝试的方式是

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]
Run Code Online (Sandbox Code Playgroud)

Sum*_*ans 5

这是使用列表理解的Pythonic方法:

s = ', '.join([str(x) + ' ' + str(a[x]) for x in a])
Run Code Online (Sandbox Code Playgroud)

输出:

'3 4, 5 6'
Run Code Online (Sandbox Code Playgroud)

更新:正如Julien Spronck所提到的,方括号([])不是必需的.因此,以下具有相同的效果:

s = ', '.join(str(x) + ' ' + str(a[x]) for x in a)
Run Code Online (Sandbox Code Playgroud)

使用PythonFiddle

  • 结果你打字更快☺ (2认同)