简体   繁体   中英

Taking a list, comparing values, creating dictionary with several keys

I am trying to take a list that has IP address and port numbers and print the data out to be in this format 127.0.0.1:21,80,443 . Here is a sample of dummy data.

127.0.0.1
80
127.0.0.1
443
192.168.1.1
21
192.168.1.2
22
192.168.1.2
3389
192.168.1.2
5900

I would like this data to output as stated above. Right now, I have the data in a list and am looking to associate the ports with the IP addresses so it is not repeating the IP address to each port. This data should output to:

127.0.0.1:80,443
192.168.1.1:21
192.168.1.2:22,3389,5900

Using a defaultdict you can collect the ports for each address, and the print them out all at once like:

from collections import defaultdict
address_to_ports = defaultdict(list)
with open('file1') as f:
    for address in f:
        address_to_ports[address.strip()].append(next(f).strip())

print(address_to_ports)

print(['{}:{}'.format(a, ','.join(p)) for a, p in address_to_ports.items()])

Results:

defaultdict(<class 'list'>, {'127.0.0.1': ['80', '443'], '192.168.1.1': ['21'], '192.168.1.2': ['22', '3389', '5900']})

['127.0.0.1:80,443', '192.168.1.1:21', '192.168.1.2:22,3389,5900']

You can use format - instead of just printing every element of the list do the following:

print "{0} : {1}".format(list[0], list[1])

You haven't specified what the input is, though. You should add it next time.

Let us suppose your list is in a file called 'ip_list.txt' The code

f = open("ip_list.txt","r")
count = 2
dict_of_ip = {}
ip = ''
for i in f:
    if count%2 == 0:
        if i.strip() not in dict_of_ip.keys():
            ip = i.strip()
            dict_of_ip[ip] = []
    else:
        dict_of_ip[ip].append(i.strip())
    count = count + 1
print(dict_of_ip)

Output:

{'192.168.1.1': ['21'], '127.0.0.1': ['80', '443']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM