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 :

JavaScript

And I looking for something like this :

JavaScript

What is the better way to did it.

This is my code :

JavaScript

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:

JavaScript

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

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