Dynamically assign values - python
Question: looking to improve the efficiency of my code, as while my current method
works, i feel it can be improved

currently this is my code :

    
    
    if ouroraddrlen == (4,):
            ouropip = struct.unpack(">bbbb", payload[6:10]) # Need to change this to accept ipv6 as well 
            print "Our I.P : ", ouropip
            notheirip = struct.unpack(">b", payload[10])
            print "No. of their I.P's : ", notheirip    
            theiroripv = struct.unpack(">b", payload[11])   
            print "Their I.P version:: ", theiroripv
            theiroraddrlen = struct.unpack(">b", payload[12])
            print "Length of their Ip : ", theiroraddrlen
            theirfirstip = struct.unpack(">bbbb", payload[13:17])
            print "First Ip : ", theirfirstip
            theirsecondip = struct.unpack(">bbbb", payload[18:22])
            print "Second Ip : ", theirsecondip
    

the output is :

    
    
    Time :  (1401734263,)
    Our onion address : 
    Ip version :  (4,)
    Ip length :  (4,)
    Our I.P :  ( )
    No. of their I.P's :  (2,)
    Their I.P version::  (4,)
    Length of their Ip :  (4,)
    First Ip :  ( )
    Second Ip :  ( )
    

i have removed the real ip's but they are just ipv4 addresses

however what i am wondering, is if it is possible to include an if statement
after this section of code :

    
    
    notheirip = struct.unpack(">b", payload[10])
            print "No. of their I.P's : ", notheirip    
    

where if the notheirip is greater than zero and depending on the length of :

    
    
            theiroraddrlen = struct.unpack(">b", payload[12])
            print "Length of their Ip : ", theiroraddrlen
    

which would be either 4 or 16 then it would set the payload values of the next
section

for example if notheirip = (2,) and theiroraddrlen = (4,) then i would want it
to print out

theirip = struct.unpack(">b << the number of b required so either 4 or 16 and
then the range, this will always start at 13 and go up to either 4 or 16 in
the future and loop until all the ip's are displayed

not sure if that is clear but hopefully it is :)

Thanks


Answer: 
    >>> from collections import namedtuple
    >>> Record = namedtuple("Record","IP NoIP IPV LenIP FirstIP SecondIP")
    >>> Record._asdict(Record._make(struct.unpack(">LbbbLL",payload[6:])))
    {'FirstIP': 1145324612, 'NoIP': 17, 'SecondIP': 1431655765, 'IP': 3140690449L,
    IPV': 34, 'LenIP': 51}
    >>>
    

I think would work (you might want different 4 byte type than L) (keep in mind
i totally made up the payload so I would expect different results with a real
one)

if you want to get 4 digit tuples for the ips just unpack the new value

    
    
    new_record["IP"] = stuct.unpack("bbbb",new_record["IP"])
    

