954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

sortig a list

I cannot seem to figure this out. This part of a larger script that I am writing. I have a list that looks like this. The fields are servername, port and program. How do I sort it to get a tally of what servers are listening on what ports.

This is my list:
[['server1', '1045', 'winlogon.exe'],
['server1', '8001', 'ctxsgsvc.exe'],
['server1', '3704', 'winlogon.exe'],
['server1', '1043', 'snmp.exe'],
['server2', '1041', 'snmp.exe'],
['server2', '1040', 'bpjava-msvc.exe'],
['server3', '2226', 'winlogon.exe'],
['server4', '1045', 'winlogon.exe'],
['server4', '1049', 'svchost.exe'],
['server5', '1048', 'clussvc.exe'],
['server5', '4660', 'winlogon.exe'],
['server5', '4911', 'winlogon.exe'],
['server6', '2226', 'winlogon.exe'],
['server6', '1045', 'winlogon.exe'],
['server6', '4998', 'unsecapp.exe'],
['server7', '4001', 'winlogon.exe']]

This is what I want:

1045 is open on server1, server4
8001 is open on server1
2226 is open on server3, server6
etc...

So far this is what I have but it doen't quite work:
allports = list(set(total.keys()))
lines = total.values()

for port in allports:
for line in lines:
if line[1] == port:
data[port] = line[0]

ccandillo
Newbie Poster
16 posts since May 2008
Reputation Points: 10
Solved Threads: 0
 

Use a dictionary, with port number as the key, pointing to a list of servers running on that port.

allports = list(set(total.keys()))
lines = total.values()

data_dict = {}
for port in allports:
    for line in lines:
        this_port = line[1]
        ## add key to dictionary if it doesn't exist, 
        ## pointing to an empty list
        if this_port not in data_dict:  
            data_dict[this_port] = []

        data_dict[this_port].append(line[0])

keys = data_dict.keys()
keys.sort()
print keys
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You