Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a list with specific rules

Tags:

python

list

I'm writing a program that analyzes DHCP packets, and came across option 43 (Vendor Specific Information). This is more of a programming question, and less technically related to networking and DHCP, therefore I tagged it as just python.

According to RFC 2132 (page 19), the structure of option 43 is as follows:

 Code   Len   Data item        Code   Len   Data item       Code
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
|  T1 |  n  |  d1 |  d2 | ... |  T2 |  n  |  D1 |  D2 | ... | ... |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

When translated to a python 'bytes' object, it should look something like this:

[T1, n, d1, d2, ..., T2, n, D1, D2, ...]

Where n is the length of the data item (Dn).

Ideally, I want to iterate over this bytes object and save the code for each data item as a key, and map it to the appropriate data item value. IE:

{T1: [d1, d2, d3], T2: [D1, D2, D3]}

For example this:

[0, 1, 2, 1, 2, 5, 6, 3, 4, 9, 10, 11, 12]

Should translate to this:

{0: [2], 1: [5,6], 3: [9, 10, 11, 12]}

Is there a correct way to do this in python?

EDIT: Also, yes. Codes (Tn) are unique.

like image 895
Alex Osheter Avatar asked Feb 06 '23 11:02

Alex Osheter


1 Answers

Use a recursive function:

trans_dict = {}
def translate(lst, trans_dict):
    if(len(lst) == 0):
        return
    else:   ​
        trans_dict[lst[0]] = lst[2:(2+lst[1])]        # the first element will be the key, 
                                                      # the value starts from the third 
                                                      # element with length of the second element
        translate(lst[(2+lst[1]):], trans_dict)

translate(lst, trans_dict)

trans_dict
# {0: [2], 1: [5, 6], 3: [9, 10, 11, 12]}
like image 172
Psidom Avatar answered Feb 07 '23 23:02

Psidom