Home > OS >  Best way to store several instances of a class inside a variable and access them based on an ID? (Py
Best way to store several instances of a class inside a variable and access them based on an ID? (Py

Time:01-04

Suppose I have a class Node which represents a point with coordinates xyz and has an integer ID.

class Node:
    def __init__(self, xyz, ID):
        [self.x, self.y, self.z] = xyz
        self.ID = ID

What's the most Pythonic way to store several instances of Node and access them based on the value of ID?

So far I've been using lists (e.g. node_lst = [node1, node2, node3, ...]) , but it feels like an overly simple solution and if I want to access a node with a specific ID I always need to search the entire list.

The values of the IDs may be arbitrary and nodes may be added or removed at will, so having the ID of each Node instance correspond to its index in the node_lst list is not an option.

CodePudding user response:

You could use a dictionary, with the ID as a key and the instance as the value.

You could then access your instances easily with the given ID, remove or add new ones also easily.

Plus it should be fast.

E.g.:

xyz = [1, 2, 3]
my_id = 230001
my_dict[my_id] = Node(xyz, my_id)

Now if you want to access your instance with 230001 as ID :

my_dict[230001]

To remove an instance:

del my_dict[my_id]
  • Related