Silin Chen Silin Chen - 1 year ago 97
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download