简体   繁体   中英

How to add json dictionaries to a list of lists

I have created some code to merge json documents (aka dictionaries) that I need to merge by looping through them and then adding them to a list of 'merged' json documents (myList).

So myList is a list of lists containing jsons!

Here is a snapshot of the code that is adding the 2 jsons. It took me a while to figure out a solution and only after I added the first line (it appears I have to initiate a new list), it worked. Otherwise I would get an 'out of index-range' error.

Is there a simpler way of doing this?

for ....
    myList.append([])
    myList[cnt].append(dict1)
    myList[cnt].append(dict2)
    cnt += 1

As mer mezba's comment. A much simpler way of doing this is

for ....
     myList.append([ dict1, dict2 ])
     cnt += 1

This will create a new list within mylist and add both json docs (as dictionaries). Adding to an existing list can still be done using eg

     myList[someExistingIndex].append(dict1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM