python - IPv4Network object as key in dictionary -
i'm using ipv4network ipaddress module keys in dict. allows me duplication quickly, , note other data.
however, i'm curious if can stack in statements , keep away o(n) processing.
from ipaddress import ipv4network net1 = ipv4network('10.10.10.0/24') net2 = ipv4network('10.10.10.128/25') net3 = ipv4network('10.10.10.0/24') dict1 = {net1: 'winner!'} print(dict1.get(net3)) winner! if net3 in dict1: print('yup') yup # -------- doesn't work, looking way accomplish it. if net2.network_address in dict1: print('wouldn't nice?) # --- yes can this. keys in dict1: if net2.network_address in keys: print(keys, 'i\'m inside you!') any ideas clever trick? way restructure leverage built-in?
i want know if
- the key exists in duplicate (easy); and
- if
ipv4networkcontained inside 1 of keys.
there's no simple way want. python's dictionary lookups use hashing efficiently find exact matches dictionary's keys. there's no way hash of network match addresses contains.
you might able write own logic test single network or address against multiple networks efficiently, code need know how ip addresses , network masks work. i'd suggest based on trie, special logic support host bits.
if want write looped code on single line, use any:
if any(net2.network_address in key key in dict1): ... but that's not nicer current code. it's not same, since any short circuits after finding single match. any code won't print multiple times if multiple keys contain net2's address. replicate any's behavior in original looping code putting break after print call in code.
Comments
Post a Comment