Skip to content
Advertisement

How to create multidimensional array in python 3 [closed]

in PHP I do the following:

<?php
   $array = array();
   for($i=0;$i<5;$i++)
   {
      $array[$i]["id"] = $i;
      $array[$i]["result"]["text"] = "id ".$i;
   }
   echo json_encode($array);

and the result is:

[{"id":0,"result":{"text":"id 0"}},{"id":1,"result":{"text":"id 1"}},{"id":2,"result":{"text":"id 2"}},{"id":3,"result":{"text":"id 3"}},{"id":4,"result":{"text":"id 4"}}]

so in python how do i do it?

UPDATE

Thanks for helping me, my question is solved, and by the time I update here there are 3 answers and I found all 3 answers did what I wanted and I decided choose and do it this way

array = []
for i in range(0,5):
    array.append({"id":i,"result":{"text":f"id {i}"}})
#dict to json
import json
print(json.dumps(array))

Because for me, I find it the most concise

Advertisement

Answer

array = []
for i in range(0,5):
    array.append({"id":i,"result":{"text":f"id {i}"}})
print(array)

#to json
import json
print(json.dumps(array))

output

[{'id': 0, 'result': {'text': 'id 0'}}, {'id': 1, 'result': {'text': 'id 1'}}, {'id': 2, 'result': {'text': 'id 2'}}, {'id': 3, 'result': {'text': 'id 3'}}, {'id': 4, 'result': {'text': 'id 4'}}]

[{"id": 0, "result": {"text": "id 0"}}, {"id": 1, "result": {"text": "id 1"}}, {"id": 2, "result": {"text": "id 2"}}, {"id": 3, "result": {"text": "id 3"}}, {"id": 4, "result": {"text": "id 4"}}]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement