How to sort IP addresses stored in dictionary in Python?

后端 未结 8 1733
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 08:32

I have a piece of code that looks like this:

ipCount = defaultdict(int)

for logLine in logLines:
    date, serverIp, clientIp = logLine.split(\" \")
    ipC         


        
8条回答
  •  广开言路
    2020-11-29 09:12

    how about not working with strings at all and instead convert each octet into integer, then passing it into 4 dimensional dictionary?

    ClientIps[192][168][102][105]=1
    ClientIps[192][168][99][11]=1
    

    then it is easy to just sort an array by key, isnt it?

    for key1, value in sorted(ClientIps.items()): 
      for key2, value in sorted(ClientIps[key1].items()): 
        for key3, value in sorted(ClientIps[key1][key2].items()): 
          for key4, value in sorted(ClientIps[key][key2][key3].items()): 
            print(key1, key2, key3, key4)
    

    for speed reasons it may be beneficial to also compare simple python dictionary against OrderedDict .

提交回复
热议问题