How to nest an appended list of dict

Question:

What I’m trying to do is take a list of dictionaries and append it as nest into a list of dictionaries. So I have the following code below:

i=1
ins = {}
meta = {}
dlist = []

# JSON data:
for i in range(0,4):
    ins['name'] = f"M {i}"
    dlist.append(ins.copy())
    print(dlist)    

which outputs this:

[
 {'name': 'M 0'}, 
 {'name': 'M 1'}, 
 {'name': 'M 2'}, 
 {'name': 'M 3'}
]

but how do I append this list nested into a dict so I can output it into json format like this:

[
  {
    "id": "",
    "meta": {
      "name": "milady ordinal #0"
    }
  },
  {
    "id": "",
    "meta": {
      "name": "milady ordinal #1"
    }
  },
  {
    "id": "",
    "meta": {
      "name": "milady ordinal #2"
    }
  },
  {
    "id": "",
    "meta": {
      "name": "milady ordinal #3"
    }
  }
]
Asked By: intermarketics

||

Answers:

Simple example with a list comprehension:

from pprint import pprint
dlist = [{'id': '', 'meta': {'name': f"M {i}"}} for i in range(4)]
pprint(dlist)

Output:

[{'id': '', 'meta': {'name': 'M 0'}},
 {'id': '', 'meta': {'name': 'M 1'}},
 {'id': '', 'meta': {'name': 'M 2'}},
 {'id': '', 'meta': {'name': 'M 3'}}]

Note: cleaning this up and reformatting the code so it is easier to read and understand, the list comprehension would look something like below:

dlist = [
    {
        'id': '',
        'meta': {
            'name': f'M {i}',
        }
     } for i in range(4)
]
Answered By: rv.kvetch
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.