将2个值放入一个dict python中

时间:2012-03-12 12:57:14

标签: python

嘿,我想把两个值放在一个字典中,我不知道如何实现这个目标。我希望它看起来像这样

{'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}}

这里是我当前的代码以及我目前在dict中获得的内容

desc_ip = {}

count_ip = 0

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

            line_of_list = line.split()

            ip_address = ' '.join(line_of_list[0:2])
            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'

这是我目前的词典

{'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}

这里有几行文件

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

4 个答案:

答案 0 :(得分:2)

date = 'Feb  7'
ip = '89.249.209.92'
count = 15

d = {}
d[date] = {ip: count}

答案 1 :(得分:1)

你需要一个dicts的词典,所以使用日期作为键并为每个日期创建一个词典。

答案 2 :(得分:0)

一个非常可扩展的答案使用AutoVivification类as shown by user Nosklo

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

使用一些示例数据:

sample_text = '''Feb 7 :  89.249.209.92
Feb 7 :  89.249.209.92
Feb 7 :  89.249.209.92
Feb 8 :  89.249.209.92
Jan 10 :  218.241.173.35'''

快速阅读数据给出:

A = AutoVivification()

for line in sample_text.split('\n'):
    date, IP = map(str.strip,line.split(':'))
    if IP not in A[date]: A[date][IP] = 0
    A[date][IP] += 1


>>>> {'Jan 10': {'218.241.173.35': 1}, 'Feb 8': {'89.249.209.92': 1}, 'Feb 7': {'89.249.209.92': 3}}

请注意,AutoVivification类不知道嵌套的深度。因此,您需要通过明确设置密钥值来设置深度,如A[date][IP] = 0

答案 3 :(得分:0)

我假设每行都有日期:

>>> sample_text = '''Feb 7 :  Failed password for 89.249.209.92
Feb 7 :  Failed password for 89.249.209.92
Feb 7 :  Failed password for 89.249.209.92
Feb 8 :  Failed password for 89.249.209.92
Jan 10 :  Failed password for 218.241.173.35'''
>>> desc_ip = {}
>>> for line in sample_text.split('\n'):
    if 'Failed password for' in line:
        line_of_list = line.split()
        ip_address = line_of_list[6]
        date = ' '.join(line_of_list[0:2])
        if not date in desc_ip:
            desc_ip[date] = {}
        if not ip_address in desc_ip[date]:
            desc_ip[date][ip_address] = 0
        desc_ip[date][ip_address] += 1


>>> desc_ip
{'Jan 10': {'218.241.173.35': 1}, 'Feb 8': {'89.249.209.92': 1}, 'Feb 7': {'89.249.209.92': 3}}
>>> 

我可以使用defaultdict来避免if not date in desc_ip等测试,但在这里我们需要defaultdict defaultdict(如desc_ip = defaultdict(lambda : defaultdict(int)))和恕我直言,降低可读性。