skip to Main Content

I want to update a list which is having one dictionary to multiple dictionaries based on the loop

ex:- i have one list it has to update as per given range

Input :

"_items": [
            {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
            }
        ]

i used

for i in range(0,5):
     json.dump(data, file, indent=4)

While using this i’m getting list index out of range error

Expected out put :

"_items": [
            {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
            },
            {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
            },
            {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
            },
            {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
            },
            {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
            }
        ]

2

Answers


  1. You could do that easily with list comprehension :

    data = [
              {
                "text": "Hi.",
                "feedback": "",
                "_score": 0
              }
            ]
    new_data = [item for item in data for i in range(n)]
    
    Login or Signup to reply.
  2. If you want to generate multiple replicas of the same element in a list, you can simply do:

    n=5
    item = [{'text': 'Hi.', 'feedback': '', '_score': 0}]
    items = item*n
    

    This will result in a list of n identical dictionaries.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search