Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

How can I copy specific items from one list to another? My original is:

[

    {

        "values" : {

            "val1"    : 334,

            "val2"   : 994,

            "val3"  : 33,

            "val4" : 345,

        },

        "filename": "image1.jpg",

    },

    {

        "values" : {

            "val1"    : 567,

            "val2"   : 777,

            "val3"  : 787,

            "val4" : 678,

        },

        "filename": "image2.jpg",

    },

]

And I want my new array to look like this:

[

    {

        "index" : 0,

        "filename": "image1.jpg",

        "val1: 334,

        "val3: 33,

    },

    {

        "index" : 1,

        "filename": "image2.jpg",

        "val1: 567,

        "val3: 787,

    },

]

I have tried this but it is not working:

for (i, x) in original:

        new.extend([{

            "index" : i,

            "filename" : x.filename,

            "val1" : x.val1,

            "val2" : x.val2,

        }])

Where am I going wrong?

1 Answer

0 votes
by (25.1k points)

Instead of using new.extend use new.append like this:

new.append({

        "index" : i,

        "filename" : x["filename"],

        "val1" : x["values"]["val1"],

        "val2" : x["values"]["val2"],

    })

Browse Categories

...