Home > Net >  In python, how can I create & maintain a list of IP addresses indexable by a pair of IP addresses?
In python, how can I create & maintain a list of IP addresses indexable by a pair of IP addresses?

Time:10-06

I'm looking for a way to maintain and update a list of IP addresses that I can index into (via a pair of IP addresses) to add a new address to the list.

For example, suppose I have an arbitrary index of (10.0.0.1 & 11.0.0.1). For that pair of indexes, I want a list of other IP addresses. I need to be able to add to the list for the pair 10.0.0.1 & 11.0.0.1 and also use something like the "in" operator to see if the addr I want to add is already present.

Something like this (the indexes are on the left and each index is a list)

(10.0.0.1, 11.0.0.1) --> [1.1.1.1, 6.7.8.9, 120.2.10.7, ...]

(17.7.1.3, 119.4.3.1) --> [33.5.1.81, 14.76.1.28, 14.9.65.19, ...] . . .

I don't really want to bother creating a database at the moment, I just want a quick temporary solution. Some time later, I'll store the info into a database.

Wondering if there are any ideas of collections that I can try.

(See the solution that I posted below, thx to the answers.)

CodePudding user response:

Dictionaries are adequate for this, as long as the key, i.e. the pair of addresses you want to index by is hashable (e.g. a tuple containing strings).

EDIT: If you haven't used dicts much yet, be aware that its elements are unordered before Python 3.6, and orderedness is only a documented feature starting with 3.7. If you only need to be compatible with Python 3.6 upwards, you may rely on the elements being in ascending order of insertion. Otherwise, you may use collections.OrderedDict instead, from the standard library.

CodePudding user response:

This appears to be working as I was hoping. I appreciate the help and gladly appreciate any additional comments.

Here's what I just tried out (using the arbitrary addresses from my original question):

>>> my_addr_dict = {}
>>> print(my_addr_dict)
{}
>>> print(type(my_addr_dict))
<class 'dict'>
>>>
>>> my_addr_dict[('10.0.0.1','11.0.0.1')]=['1.1.1.1']
>>> my_addr_dict[('10.0.0.1','11.0.0.1')].append('6.7.8.9')
>>> my_addr_dict[('10.0.0.1','11.0.0.1')].append('120.2.10.7')
>>>
>>> print(my_addr_dict)
{('10.0.0.1', '11.0.0.1'): ['1.1.1.1', '6.7.8.9', '120.2.10.7']}
>>>
>>> print(type(my_addr_dict['10.0.0.1','11.0.0.1']))
<class 'list'>
>>>
>>> my_addr_dict[('17.7.1.3','119.4.3.1')]=['33.5.1.81']
>>> my_addr_dict[('17.7.1.3','119.4.3.1')].append('14.76.1.28')
>>> my_addr_dict[('17.7.1.3','119.4.3.1')].append('14.9.65.19')
>>>
>>> print(my_addr_dict)
{('10.0.0.1', '11.0.0.1'): ['1.1.1.1', '6.7.8.9', '120.2.10.7'], ('17.7.1.3', '119.4.3.1'): ['33.5.1.81', '14.76.1.28', '14.9.65.19']}
>>>
>>> print(my_addr_dict[('10.0.0.1','11.0.0.1')])
['1.1.1.1', '6.7.8.9', '120.2.10.7']
>>> print(my_addr_dict[('17.7.1.3','119.4.3.1')])
['33.5.1.81', '14.76.1.28', '14.9.65.19']
>>>
  • Related