add indexes on the fly to lists

G

Gabriel B.

I wanted to make a list index work as the index of the data in the
database. something like

database:
idx
item_description
item_value

being imported to my program as:
x[idx][0]= item_description
x[idx][1]= item_value

the problem is that there will be some hundred items and possible the
idx wil vary from 1 to 600 (it's not linear as items got deleted the
idx should not be reused)

will it still be an easy solution or just a waste of resources (having
a 600-sized list for 100 elements)

I'm very new to python and apreciate any hints on that.

Thanks
Gabriel
 
D

Diez B. Roggisch

The data structure you want to use is a dictionary - known as hashmap or
hash or map in other languages. Lets say you have a few objects of type
town that you want to access using their zip, then things could look like
this:

------------
class Town(object):
def __init__(self, zip, cool_clubs):
self.zip = zip
self.colo_clubs = cool_clubs


towns = [Berlin(10439, ["Marietta", "ICON", "Bastart"]),
Cologne(50000, ["Subway", "Stadtgarten", "Gebäude 9"])]

index = {}
for town in towns:
index[town.zip] = town
 
D

Do Re Mi chel La Si Do

Hi !

If you want only "search and found" element, look dictionnary ; if you want
also to have the order, see the module set.

Good night
 
D

Diez B. Roggisch

If you want only "search and found" element, look dictionnary ; if you
want also to have the order, see the module set.

Erg - no. Sets are mathematically defined as having no order.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top