Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python inserting in an empty list at specific index doesn't work

I have a list of object, each object contains a unique ID. The current list is like so:

[{"id": 3}, {"id": 5}, {"id": 8}]

I want to change the indexes a bit – instead of the dictionary with id = 3 to be on index 0, I want the dictionary with id = 3 to be on index 3.

I have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list = []
for item in items:
    list[item["id"]] = item

but that gives me indexing error. Then I tried to do the following:

list = []
for item in items:
    list.insert(item["id"], item)

which just acts like a regular append (does not insert at specified index).

I have a last ditch attempt to do this on the front end when I am getting the response from the API but that defeats the whole purpose of reducing the amount of looping I do on the client side. The reason being is that the server can knock out these loops in like 50 milliseconds and on the client side it takes up to 300 milliseconds since it runs in the browser.

>Solution :

There is no problem in your code it all happens because your list has zero element

items = [{"id": 3}, {"id": 5}, {"id": 8}]
list_ = []
for item in items:
    while item['id'] > len(list_):
        list.append(None)
    list_.insert(item["id"], item)
print(list_)

OUTPUT:

You can see here your elements are inserted inside the list.

[None, None, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}, None]

The above code works perfectly if the dictionary inside the list is in increasing order, But if the dictionary is in random order then first you need to first change the list to increasing order.


items = [{"id": 3}, {"id": 5}, {"id": 8},{'id':2}]
items = (sorted(items,key=lambda e:e['id'])) # sort the list
list_ = [] 
for item in items:
    while item['id'] > len(list_):
        list.append(None)
    list_.insert(item["id"], item)
print(list)

INPUT/OUTPUT

IN:items = [{"id": 3}, {"id": 5}, {"id": 8},{'id':2}]

OUTPUT FROM FIRST ANSWER:[None, None, {'id': 2}, None, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}]

OUTPUT FROM SECOND ANSWER:[None, None, {'id': 2}, {'id': 3}, None, {'id': 5}, None, None, {'id': 8}]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading