Skip to content
Advertisement

Python add missing element into list

I have a list with day of a month as key and i want to add all missing day with 0 as value.

This is a sample :

tab = [{'day':3, 'value':50, 'label': 'Element 1' }, {'day':5, 'value':20, 'label': 'Element 2'},{'day':11, 'value':3, 'label': 'other label'},{'day':15, 'value':5, 'label': 'something'}]

And I looking for something like this :

tab = [{'day':1, 'value':0, 'label': 'some label'}, {'day':2, 'value':0, ‘label': 'something'}, ...,{'day':30, 'value':0, 'label': 'value label'}]

What is the better way to did it.

This is my code :

new_tab = []
for i in range(1, 30):
    if i not in existing_day:
        new_tab.append({'day': i, 'value': 0, 'label':''})
    else:
        elt = [x for x in tab if x['day'] == i]
        new_tab.append(elt[0])

Advertisement

Answer

You could simply make a run with numbers varying from 1 to 31, and add the mssing parts in there. However, the list of records itself, as is, is bad for retrieving data on a given day: one simply can’t do tab[3] to get information on “day 3”, which would be O(1), instead one has to perform a search of the whole list, checking each record for r['day'] == 3 which is a linear search.

You can create a class that will act as a mapping for whoever is using it, index the records by day, and return an appropriate default record when there is no data for a given day.

It can be sophisticated, but ultimately, all you need is a class that will create the index as a dictionary, and feature a __getitem__ method:

class TabIndex:
    def __init__(self, tab):
        self.indexed = {record["day"]: record for record in tab}

    def __getitem__(self, index):
        return self.indexed.get(index, {"day": index, "value": 0})

And here is how you can use this, demonstrated on an interactive session:

In [41]: tab = [{'day':3, 'value':50, 'label': 'Element 1' }, {'day':5, 'value':20, 'label': 'Element 2'},{'day':11, 'value':3, 'label': 'other label'},{'day':15, 'value':5, 'label': 'something'}]

In [42]: x= TabIndex(tab)

In [43]: x[20]
Out[43]: {'day': 20, 'value': 0}

In [44]: x[3]
Out[44]: {'day': 3, 'value': 50, 'label': 'Element 1'}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement