在python循环中构建dict

时间:2018-01-04 21:21:20

标签: python dictionary

我几天前提出了一个问题:Building a connection log system

此代码:

import re

f = open('log.log', 'r')
log = dict()
for line in f:
    reg = re.search(r': ((?:dis)?connected)', line) # finds connected or disconnected
    if reg is not None:
        user = re.search(r'<pppoe-(.*?)>', line).group(1)
        # if the user in the log, get it, else create it with empty dict
        ob = log.setdefault(user, dict({'USER': user})) 
        ob['CONNECTION'] = reg.group(1)
        time = re.search(r'^\w{3} \d{2} \d{2}:\d{2}:\d{2}', line).group(0)
        if ob['CONNECTION'].startswith('dis'):
            ob['END'] = time
        else:
            ob['START'] = time
            if 'END' in ob:
                ob.pop('END')

var log:

{
    'customer1': {
        'CONNECTION': 'disconnected',
        'END': 'Dec 19 00:00:03',
        'USER': 'customer1'
    }, 
    'customer3': {
        'START': 'Dec 19 00:02:08',
        'CONNECTION': 'connected',
        'USER': 'customer3'
    }, 
    'customer2': {
        'START': 'Dec 19 00:00:08',
        'CONNECTION': 'disconnected',
        'END': 'Dec 19 00:02:03', 
        'USER': 'customer2'
    }
}

现在我将把[&#39; USER&#39;]值作为参数传递给此函数。因为我需要获取有关USER的更多信息,所以..所有代码

import re


    def getUser(user):
     conn = databaseConnection()
     cur = conn.cursor()
     conn.set_client_encoding('LATIN1')
     rows = cur.execute("SELECT * FROM users WHERE username=%s",(user,))
     rows = cur.fetchall()
     return rows

    f = open('log.log', 'r')
    log = dict()
    for line in f:
        reg = re.search(r': ((?:dis)?connected)', line) # finds connected or disconnected
        if reg is not None:
            user = re.search(r'<pppoe-(.*?)>', line).group(1)
            # if the user in the log, get it, else create it with empty dict
            ob = log.setdefault(user, dict({'USER': user})) 
            ob['CONNECTION'] = reg.group(1)
            time = re.search(r'^\w{3} \d{2} \d{2}:\d{2}:\d{2}', line).group(0)
            if ob['CONNECTION'].startswith('dis'):
                ob['END'] = time
            else:
                ob['START'] = time
                if 'END' in ob:
                    ob.pop('END')

    newDict = dict()    
    for i in log.itervalues(): #Iterate log values...     
     if i['CONNECTION'] == 'disconnected': #Now I need to take the CONNECTION that has the "disconnected" value     
      users = getUser(i['USER']) #Here I have all users that has this condition, now I can call the method      
      for user in users: #Create a new dict with both informations
       ob = newDict.setdefault(user[0], {'CUSTOMER': user[0]})
       ob['NAME'] = user[1]
       ob['CITY'] = user[2]
       ob['END'] = i['END']

print newDict # Just one row, instead of print more than one if I print inside for loop

我期待newDict输出的结果是什么..

{
        'customer1': {
            'NAME': 'Peter',
            'City': 'California'
            'END': 'Dec 19 00:00:03',
        }, 
        'customer3': {
            'NAME': 'Carl',
            'City': 'New York'
            'END': 'Dec 19 00:00:03',
        }, 
        'customer2': {
            'NAME': 'Matt',
            'City': 'New York'
            'END': 'Dec 19 00:00:03',
        }
    }

如果我在de loop中打印newDict,我只得到那个结果。

 .....
for user in users: #Create a new dict with both informations
               ob = newDict.setdefault(user[0], {'CUSTOMER': user[0]})
               ob['NAME'] = user[1]
               ob['CITY'] = user[2]
               ob['END'] = i['END']
               print newDict

在这个循环之外:

{
        'customer1': {
            'NAME': 'Peter',
            'City': 'California'
            'END': 'Dec 19 00:00:03',`
}}

1 个答案:

答案 0 :(得分:0)

我刚刚修改了我的代码并更改了一些行并进行了操作。现在我可以打印出我所期待的所有行!

dict = {}    
for i in log.itervalues(): 
 if i['CONNECTION'] == 'disconnected': 
  username = i['USER']
  users = getUser(username) 
  for u in users: 
   ob = dict.setdefault(u[0], {'CUSTOMER': u[0]})
   ob['NAME'] = u[1]
   ob['CITY'] = u[2]
   ob['END'] = i['END']