Silin Chen Silin Chen - 11 months ago 54
Python Question

convert dictionaries into string python

I am trying to convert dictionaries into string

for example:

s='3 4, 5 6'

The way I am trying is

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):

Answer Source

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

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


'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