Kevin R. Kevin R. - 4 months ago 7
Python Question

Adding lines of a text file to a dictionary

I've been trying to think how I would exactly do this, but I cant seem to get anywhere.

If I have a text file that contains a host name with their made up corresponding ip address:

The result of www.espn.com is 199.181.133.15
The result of www.espn.com is 199.454.152.10
The result of www.espn.com is 20.254.215.14
The result of www.google.com is 141.254.15.14
The result of www.google.com is 172.14.54.153
The result of www.yahoo.com is 181.145.254.12


How could I get the address and their corresponding ip address in a list or dictionary?

So like for
www.google.com
would be something like:

("www.google.com", 141.254.15.14, 172.14.54.153)


The lines above will always be in the same format, so I could iterate over the file, take the above, use
split()
, and add the addresses to a dictionary.

.......
....
dictA = {}
for line in f:
splitLine = line.split()
dictA = {splitLine[2]: splitLine[3]}


The key would be just the website, and the values would be all of its corresonpding ip addresses. I just need to get them inside a list or something togethe.

Answer

You can make use of defaultdict from collections and set your default as a list:

>>> from collections import defaultdict
>>> s = '''The result of www.espn.com is 199.181.133.15
... The result of www.espn.com is 199.454.152.10
... The result of www.espn.com is 20.254.215.14
... The result of www.google.com is 141.254.15.14
... The result of www.google.com is 172.14.54.153
... The result of www.yahoo.com is 181.145.254.12'''.splitlines()
>>> dictA = defaultdict(list)
>>> for 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']})

>>> for 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']