hey i want to put two values into one dict and am not sure how to achieve this. i want it to look like this. what am trying to do is a dictionary that holds the date as the key, and a dictionary as its value. That dictionary will contain the ip addresses encountered as keys, and the number of times they've been counted as values.

{'Feb 7': {'89.249.209.92': 15},
'Feb 8': {'66.30.90.148': 14, '72.153.93.203': 14, '92.152.92.123': 5},
'Jan 10': {'213.251.192.26': 13, '218.241.173.35': 15}}

here my current code and what i currently getting in dict

myfile = open('auth','r')

desc_ip = {}
desc_ip['date'] = {} 

count_ip = 0

for line in myfile:
    if 'Failed password for' in line:

        line_of_list = line.split()

        ip_address_port = ' '.join(line_of_list[0:2])
        ip_address_list = ip_address_port.split(':')
        ip_address = ip_address_list[0]
        if desc_ip['date'].has_key(ip_address):
            desc_ip['date'] = ip_address
            
            
        ip_address = line_of_list[-4]
        if ip_address in desc_ip:
            count_ip = desc_ip[ip_address]
            count_ip = count_ip +1
            desc_ip[ip_address] = count_ip
            #zero out the temporary counter as a precaution
            count_ip =0
        else:
            desc_ip[ip_address] = 1


for ip in desc_ip.keys():
	print ip ,' has', desc_ip[ip] , ' attacks'

here my current dict

{'213.251.192.26': 13,
'218.241.173.35': 15,
'66.30.90.148': 14,
'72.153.93.203': 14,
'89.249.209.92': 15,
'92.152.92.123': 5}

here a few lines from the file

Jan 10 09:32:09 j4-be03 sshd[3876]: Failed password for root from 218.241.173.35 port 47084 ssh2
Feb 7 17:19:24 j4-be03 sshd[10740]: Failed password for root from 89.249.209.92 port 46752 ssh2

Edited 4 Years Ago by welshly_2010: current code was wrong

Use a list

some_dict={}
for key in ["a", "b", "a", "c", "c"]:
    if key not in some_dict:
        some_dict[key]=[]
    some_dict[key].append(key)

print some_dict

Edited 4 Years Ago by woooee: n/a

PS, is there a list comprehension way to do this in 1-2 lines? I use this so often that I'd like to shorten the syntax.

Don't know the structure of your data, but the previous example other way:

data = "abacc"
some_dict={key:[k for k in data if k == key] for key in set(data)}

print some_dict
This article has been dead for over six months. Start a new discussion instead.