I have multiple variables that I need to pack as one and hold it sequentially like in a array or list. This needs to be done in Python and I am still at Python infancy.
E.g. in Python:
a = Tom
b = 100
c = 3.14
d = {'x':1, 'y':2, 'z':3}
All the above in one sequential data structure. I can probably try and also a similar implementation I would have done in C++ just for the sake of clarity.
struct
{
string a;
int b;
float c;
map <char,int> d;// just as an example for dictionary in python
} node;
vector <node> v; // looking for something like this which can be iterable
If some one can give me a similar implementation for storing, iterating and modifying the contents would be really helpful. Any pointers in the right direction is also good with me.
Thanks
You can either use a dictionary like Michael proposes (but then you need to access the contents of
vwithv['a'], which is a little cumbersome), or you can use the equivalent of C++’s struct: a named tuple:This is similar to, but simpler than defining your own class:
type(v) == node, etc. Note however, as volcano pointed out, that the values stored in anamedtuplecannot be changed (anamedtupleis immutable).If you indeed need to modify the values inside your records, the best option is a class:
The last option, which I do not recommend, is indeed to use a list or a tuple, like ATOzTOA mentions: elements must be accessed in a not-so-legible way:
node[3]is less meaningful thannode.last_name; also, you cannot easily change the order of the fields, when using a list or a tuple (whereas the order is immaterial if you access a named tuple or custom class attributes).Multiple
nodeobjects are customarily put in a list, the standard Python structure for such a purpose:or
or
etc. The best method depends on how the various
nodeobjects are created, but in many cases a list is likely to be the best structure.Note, however, that if you need to store something akin to an spreadsheet table and need speed and facilities for accessing its columns, you might be better off with NumPy’s record arrays, or a package like Pandas.