0

I have dictionary in python script like this

{key:value}
{key:value}
{key:value}  

I wanted to make it into a single key dictionary like

[{'key':value} , {'key:value} , {'key':value}......]

My code is below:

for (recActorIMDBid, recActorName, recActorTopTen) in cursor:  

    recActorTopTen = str(recActorTopTen).replace(",", "_ ")
    contentIDArray =[]
    contentIDArray = recActorTopTen.split("_ ")
    if len(contentIDArray) > 9:

        stringOut = "ID," + str(recID) + ",IMDB ID," + str(recActorIMDBid) + ",NAME," + str(recActorName) + ",TOP TEN," \ + str(recActorTopTen)

        print(stringOut)

I need to change the result to json, what should I Do?

Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
Avz Vicky
  • 11
  • 9
  • 3
    Your desired output is not a single key dictionary, but a list of single-keyed dictionaries. In order to achieve that create a list and append them to it. – Sergio Oct 16 '18 at 10:11

2 Answers2

0

This will work:

dict1 = {0: 5, 1: 8, 2: 3}
dict2 = {0: 6, 1: 2, 2: 4}
dict3 = {0: 7, 1: 9, 2: 2}
dicts = []
dicts.append(dict1)
dicts.append(dict2)
dicts.append(dict3)
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
0

Just iterate over items() (key-value pairs) and use a list comprehension

[{k: v} for k, v in my_dict.items()]

Note: I'm assuming your question has a few typos, because what you describe is not exactly valid.

blue_note
  • 27,712
  • 9
  • 72
  • 90
  • I am processing some data( like associative array ) and return the response as JSON. – Avz Vicky Oct 16 '18 at 10:19
  • for (recActorIMDBid, recActorName, recActorTopTen) in cursor: recActorTopTen = str(recActorTopTen).replace(",", "_ ") contentIDArray =[] contentIDArray = recActorTopTen.split("_ ") if len(contentIDArray) > 9: stringOut = "ID," + str(recID) + ",IMDB ID," + str(recActorIMDBid) + ",NAME," + str(recActorName) + ",TOP TEN," \ + str(recActorTopTen) print(stringOut) the above code returns string i need to change this format to json what should i do. – Avz Vicky Oct 16 '18 at 10:19
  • @AvzVicky: move the code into your question, it's unreadable here. – blue_note Oct 16 '18 at 10:21
  • Added the code in question sections. my requirement was return response as json . – Avz Vicky Oct 16 '18 at 10:51