i've been trying think how this, cant seem anywhere.
if have text file contains host name made corresponding ip address:
the result of www.espn.com 199.181.133.15 result of www.espn.com 199.454.152.10 result of www.espn.com 20.254.215.14 result of www.google.com 141.254.15.14 result of www.google.com 172.14.54.153 result of www.yahoo.com 181.145.254.12
how address , corresponding ip address in list or dictionary?
so www.google.com
like:
("www.google.com", 141.254.15.14, 172.14.54.153)
the lines above in same format, iterate on file, take above, use split()
, , add addresses dictionary.
....... .... dicta = {} line in f: splitline = line.split() dicta = {splitline[2]: splitline[3]}
the key website, , values of corresonpding ip addresses. need them inside list or togethe.
you can make use of defaultdict
collections
, set default list:
>>> collections import defaultdict >>> s = '''the result of www.espn.com 199.181.133.15 ... result of www.espn.com 199.454.152.10 ... result of www.espn.com 20.254.215.14 ... result of www.google.com 141.254.15.14 ... result of www.google.com 172.14.54.153 ... result of www.yahoo.com 181.145.254.12'''.splitlines() >>> dicta = defaultdict(list) >>> line in s: ... words = line.split() ... dicta[words[3]].append(words[-1]) ... >>> dicta defaultdict(<type 'list'>, {'www.yahoo.com': ['181.145.254.12'], 'www.espn.com': ['199.181.133.15', '199.454.152.10', '20.254.215.14'], 'www.google.com': ['141.254.15.14', '172.14.54.153']}) >>> key, val in dicta.items(): ... print key, val ... www.yahoo.com ['181.145.254.12'] www.espn.com ['199.181.133.15', '199.454.152.10', '20.254.215.14'] www.google.com ['141.254.15.14', '172.14.54.153']
Comments
Post a Comment