Search code examples
pythonpython-3.xlistappenddefaultdict

How to insert values at specific index in defaultdict in Python3


i'm a beginner on Python and what i'm trying to do is adding an element in a specific index in a list of values associated to my key in Python 3, using defaultdict.

My default_dict structure is the following:

default_dict = ['label_1':[list of doubles], 'label_2':[list of doubles], etc..]

suppose i have a double d = 6.5 and i want to insert it as a value of the list with key: label_1 in a specific index.

if my list is:[12.3, 11.8, 8.6, 5.8, 3.1]

i would like to insert my d = 6.5 between 8.6 and 5.8

i know a call like default_dict[label_1].append(d) would result in a list like that:

[12.3, 11.8, 8.6, 5.8, 3.1, 6.5]

is there a function i can use like: default_dict[label_1].add(d, index_to_insert) ?

i thought i could fetch the entire list, modify it by myself and switch the new one with the old i had but i think this is a onerous call (i need to call that a lot of time) and i need a more efficient way!

Thanks in advance!


Solution

  • Use list.insert(index,object) for adding into specific index of List.

    Please note you have to do this for inside list you have in default_dict as you are referring.

    ex:

    >>li1 = [1,2,3,4,5]
    >>li1.insert(5,8)
    >>li1
    [1, 2, 3, 4, 5, 8]
    >>li1.insert(1,99)
    >>li1
    [1, 99, 2, 3, 4, 5, 8]
    

    More efficient way is slicing too, if you are inserting single or multiple elements at specific index without replacing existing values.

    >>li1 = [1,2,3,9,6,4,9,0]
    >>li1[3:3] = [7]
    >>li1
    [1, 2, 3, 7, 9, 6, 4, 9, 0]
    

    Please note time complexity for insert is O(n) and slicing is O(k)