0

I have some python code that appends a results object to a list.

objs = []
objs.append(results['Contents'])

If I print results['Contents'], it looks like this:

[
   {
      "id": 1,
      "name", "joe"
   },
   {
      "id": 2,
      "name", "jane"
   },
   {
      "id": 3,
      "name", "john"
   }
]

However, when I print objs, it looks like this - as you can see it is now a list within a list:

[
   [
      {
         "id": 1,
         "name", "joe"
      },
      {
         "id": 2,
         "name", "jane"
      },
      {
         "id": 3,
         "name", "john"
      }
   ]
]

This starts to cause me issues as I begin to loop through and append more objects (that are structured just like results['Contents']) as follows:

objs.append(l_objs['Contents'])

As I end up with something like this:

[
   [
      {
         "id": 1,
         "name", "joe"
      },
      {
         "id": 2,
         "name", "jane"
      },
      {
         "id": 3,
         "name", "john"
      }
   ],
   [
      {
         "id": 4,
         "name", "pete"
      },
      {
         "id": 5,
         "name", "paul"
      },
      {
         "id": 6,
         "name", "pat"
      }
   ]
]

What I'm really looking for is something like this:

[
   {
      "id": 1,
      "name", "joe"
   },
   {
      "id": 2,
      "name", "jane"
   },
   {
      "id": 3,
      "name", "john"
   },
   {
      "id": 4,
      "name", "pete"
   },
   {
      "id": 5,
      "name", "paul"
   },
   {
      "id": 6,
      "name", "pat"
   }
]

Is it possible to append these result arrays together so that they form one combined object?

I'd expect len(objs) to equal 6 in my example as opposed to 2

martineau
  • 119,623
  • 25
  • 170
  • 301
nimgwfc
  • 1,294
  • 1
  • 12
  • 30

2 Answers2

5

You need to use extend instead of append.

objs = []
objs.extend(results['Contents'])
Jeechu Deka
  • 354
  • 1
  • 4
  • [link to a w3 page about `list.extend`](https://www.w3schools.com/python/ref_list_extend.asp) – Roy Cohen Mar 09 '21 at 17:39
  • @RoyCohen -[https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) – wwii Mar 09 '21 at 22:30
  • I don't have an object, I want to do something like this `objs.append({'number': parseInt(aNumber), 'PK': parseInt(aNotherNumber)}` – AnonymousUser Jun 19 '22 at 04:07
0

This can be done via the extend function, like so:

objs = []
objs.extend(results['Contents']
prints objs

Alternatively, you can loop through results['Contents'], and use append:

objs = []
for item in results['Contents']:
    objs.append(item)
print(objs)
CATboardBETA
  • 418
  • 6
  • 29