how to convert list of dictionary into string

Viewed 7227

Example is given below this is the list that contains so many dictionaries

l = [{'ID': '4901454'}, {'ID': '5722619'}, {'ID': '5722619'}]

Expected output string is

>>> result = '4901454,5722619,5722619'

Any help would be appreciated

2 Answers

You can use a list comprehension to iterate over the dicts in the list and for each dict get the value for the id and then with the returning list of id vals join them with a comma.

data = [{'ID': '4901454'}, {'ID': '5722619'}, {'ID': '5722619'}]
string = ",".join([item['ID'] for item in data])
print(string)

OUTPUT

4901454,5722619,5722619

If you know the keys before hand then it is quite trivial. Iterate through the list and then join into one string.

l = [{'ID': '4901454'}, {'ID': '5722619'}, {'ID': '5722619'}]
s = []
for i in range(len(l)):
     s.append(l[i]['ID'])
result = ','.join(s)
Related