Silin Chen Silin Chen - 1 month ago 8
Python Question

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]

Answer

Here's a Pythonic way of doing that using a list comprehension:

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. Thus, the following has the same effect:

s = ', '.join(str(x) + ' ' + str(a[x]) for x in a)

Working PythonFiddle


Further Reading:

Python List Comprehensions at StackOverflow Documentation