data structure

Paul Barry paul.james.barry at gmail.com
Thu Jun 15 03:07:10 EDT 2017


Hi Andrew.

You start by talking about a data structure, then show code that uses
"class".  Not everything in Python needs to be in a class.

I'd look at using a simple Dictionary of lists, indexed on your ID.  A list
can contain anything, so you can add your objects in there dynamically as
needed.  If you need to refer to the objects by name, use a dictionary of
dictionaries.

Examples:

# Dict of lists.

>>> my_objects = {}
>>> my_objects['id1'] = []
>>> my_objects
{'id1': []}
>>> my_objects['id2'] = []
>>> my_objects
{'id1': [], 'id2': []}
>>> my_objects['id3'] = []
>>> my_objects
{'id1': [], 'id2': [], 'id3': []}
>>> my_objects['id2'].append('some data, but could be anything')
>>> my_objects
{'id1': [], 'id2': ['some data, but could be anything'], 'id3': []}
>>> my_objects['id2'][0]
'some data, but could be anything'

# Dict of dicts.

>>> my_objects2 = {}
>>> my_objects2['id1'] = {}
>>> my_objects2['id2'] = {}
>>> my_objects2['id3'] = {}
>>> my_objects2
{'id1': {}, 'id2': {}, 'id3': {}}
>>> my_objects2['id2']['new_key'] = 'some data, but could be anything'
>>> my_objects2
{'id1': {}, 'id2': {'new_key': 'some data, but could be anything'}, 'id3':
{}}
>>> my_objects2['id2']['new_key']
'some data, but could be anything'

I think if you concentrate on manipulating your data as opposed to trying
to write code which manipulates it, you might be better off.

I hope this helps.

Regards.

Paul.





On 15 June 2017 at 02:36, Andrew Zyman <formisc at gmail.com> wrote:

> Hello,
>  i wonder what would be a proper data structure for something with the
> following characteristics:
>
> id - number,
> obj[a..c] - objects of various classes
>
> the idea is to be able to update certain fields of these objects initially
> getting access to the record by ID
>
> something like this ( not working )
>
> ### code start
>
> class ClassA(object):
>     a = ''
>     b = ''
>     def __init__(self):
>         a= 'aa'
>         b= 'ab'
>
> class ClassB(object):
>     def __init__(self):
>         self.c = 'ba'
>         self.d = 'bb'
>
> def main():
>     obja = ClassA
>     objb = ClassB
>
>     sets = set(obja, objb)
>     contracts[1] = sets
>
>     print('Sets ', contracts)
>
> # with the logic like ( not working too)
>         if obja.a = 'aa':
>             contracts[1].obja.a = 'ABC'
>
>
>  if __name__ == '__main__':
>     main()
>
>
> ### code end
>
> appreciate your guidance
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Paul Barry, t: @barrypj <https://twitter.com/barrypj> - w:
http://paulbarry.itcarlow.ie - e: paul.barry at itcarlow.ie
Lecturer, Computer Networking: Institute of Technology, Carlow, Ireland.



More information about the Python-list mailing list