Python-使用列表作为值创建字典

Python-使用列表作为值创建字典,python,Python,我有一个下面格式的绑定文件 BIND REQ conn=8349228 op=0 msgID=1 version=3 type=SIMPLE dn="uid=test1,ou=Users,ou=Internal,o=example" BIND REQ conn=8349229 op=0 msgID=1 version=3 type=SIMPLE dn="uid=test1,ou=Users,ou=Internal,o=example" BIND REQ conn=8349230 op=0 msg

我有一个下面格式的绑定文件

BIND REQ conn=8349228 op=0 msgID=1 version=3 type=SIMPLE dn="uid=test1,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349229 op=0 msgID=1 version=3 type=SIMPLE dn="uid=test1,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349230 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349231 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349232 op=0 msgID=1 version=3 type=SIMPLE dn="uid=COVESEOS,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349233 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349235 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349234 op=0 msgID=1 version=3 type=SIMPLE dn="uid=COVESEOS,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349236 op=0 msgID=1 version=3 type=SIMPLE dn="uid=COVESEOS,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349237 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349238 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349239 op=0 msgID=1 version=3 type=SIMPLE dn="uid=COVESEOS,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349240 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349241 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"
BIND REQ conn=8349242 op=0 msgID=1 version=3 type=SIMPLE dn="uid=xdev,ou=Users,ou=Internal,o=example"`
现在我要做的是创建一个
{'uid':[connections-id]}
格式的字典,例如如下所示

{'test1' : [8349228,8349229,...],
 'xdev' : [8349230,8349231,...],
 ...so on  }`

有人能在这方面指导我吗!!非常感谢您的帮助。

这种方法应该可以。读取文件时,调用此方法,它将以指定的格式返回dict

import re
def input_to_dict(inp):  # inp = input from text file
    for line in inp.split("\n"):
        pattern = re.compile("uid=([A-Za-z0-9]{1,}),")
        id_pattern = re.compile("conn=([0-9]{1,})")
        name = pattern.search(line).group(1)
        c_id =id_pattern.search(line).group(1)
        if name in d.keys():
            d[name].append(c_id)
        else:
            d[name] = [c_id]
    return d
用法示例:

with open("file.txt", "r") as file:
    lines = file.readlines()
    d = input_to_dict(lines)

这种方法应该可以做到这一点。读取文件时,调用此方法,它将以指定的格式返回dict

import re
def input_to_dict(inp):  # inp = input from text file
    for line in inp.split("\n"):
        pattern = re.compile("uid=([A-Za-z0-9]{1,}),")
        id_pattern = re.compile("conn=([0-9]{1,})")
        name = pattern.search(line).group(1)
        c_id =id_pattern.search(line).group(1)
        if name in d.keys():
            d[name].append(c_id)
        else:
            d[name] = [c_id]
    return d
用法示例:

with open("file.txt", "r") as file:
    lines = file.readlines()
    d = input_to_dict(lines)

这些步骤是:

Create empty dictionary 
Loop through lines in input file 
    Find values of `uid` and `conn` (easiest way using regex)
    Check if current `uid` exists in dictionary 
        It doesn't, create new entry with current `uid` as key and empty list as value.
    Append `conn` to list associated to `uid` key
向dict添加键和值 要向dict添加键和值,应使用:

if somekey not in dict1.keys():
    dict1[somekey] = []
dict1[somekey].append(somevalue)

您不应该使用任何“外部”列表,只使用字典中创建的列表。

以下是步骤:

Create empty dictionary 
Loop through lines in input file 
    Find values of `uid` and `conn` (easiest way using regex)
    Check if current `uid` exists in dictionary 
        It doesn't, create new entry with current `uid` as key and empty list as value.
    Append `conn` to list associated to `uid` key
向dict添加键和值 要向dict添加键和值,应使用:

if somekey not in dict1.keys():
    dict1[somekey] = []
dict1[somekey].append(somevalue)

您不应该使用任何“外部”列表,只使用在字典中创建的列表。

如注释所示,您可以使用
列表
默认值。然后只需为文件中的每一行运行正则表达式,并将uid和连接id捕获到添加到结果中的两个组:

import re
from collections import defaultdict

res = defaultdict(list)
with open('log.txt') as f:
    for line in f:
        m = re.search('conn=([\w]*).*uid=([^,]*)', line)
        conn_id, uid = m.group(1, 2)
        res[uid].append(conn_id)

print(res)
输出:

defaultdict(<type 'list'>, {
   'test1': ['8349228', '8349229'], 
   'xdev': ['8349230', '8349231', '8349233', '8349235', '8349237', '8349238', '8349240', '8349241', '8349242'], 
   'COVESEOS': ['8349232', '8349234', '8349236', '8349239']
})
defaultdict({
'test1':['8349228','8349229'],
‘xdev’:[‘8349230’、‘8349231’、‘8349233’、‘8349235’、‘8349237’、‘8349238’、‘8349240’、‘8349241’、‘8349242’],
“COVESEOS”:['8349232','8349234','8349236','8349239']
})

如注释所示,您可以使用
列表
默认值。然后只需为文件中的每一行运行正则表达式,并将uid和连接id捕获到添加到结果中的两个组:

import re
from collections import defaultdict

res = defaultdict(list)
with open('log.txt') as f:
    for line in f:
        m = re.search('conn=([\w]*).*uid=([^,]*)', line)
        conn_id, uid = m.group(1, 2)
        res[uid].append(conn_id)

print(res)
输出:

defaultdict(<type 'list'>, {
   'test1': ['8349228', '8349229'], 
   'xdev': ['8349230', '8349231', '8349233', '8349235', '8349237', '8349238', '8349240', '8349241', '8349242'], 
   'COVESEOS': ['8349232', '8349234', '8349236', '8349239']
})
defaultdict({
'test1':['8349228','8349229'],
‘xdev’:[‘8349230’、‘8349231’、‘8349233’、‘8349235’、‘8349237’、‘8349238’、‘8349240’、‘8349241’、‘8349242’],
“COVESEOS”:['8349232','8349234','8349236','8349239']
})

hi首先创建一个用于匹配所有所需值的正则表达式,然后使用uid创建一个dict(如果该键存在),更新列表,如果为dict创建一个新的正则表达式,则使用集合
d=defaultdict(list)
中的defaultdict(list)您卡在哪里?我已经创建了用于匹配所需模式的te正则表达式,这是我第一次能够通过将conn id追加到list来创建以key作为uid和值的dict。问题是如果uid再次出现,我如何将其值追加到list中。&因为有很多uid,我无法创建动态列表。这是我的代码
import re-dict1={}conid=[]fh=open(“C:\\test”,“r”),用于fh:if-re.search中的行(“BIND REQ”,line):conid.append(line.split()[4])dict1[line.split()[-1]。split(“,”[0]]=conid fh.close()打印(len(dict1['dn=“uid=test1']))
print的输出是整个文件中的行数,但我希望uidhi首先创建一个正则表达式以匹配所有要求的值,然后使用uid创建一个dict,如果该键存在,则更新列表,如果一个新的,则为dict创建一个新键使用集合
defaultdict
d=defaultdict(列表)你被困在哪里了?我已经创建了te正则表达式来匹配所需的模式,这是我第一次能够通过将conn id附加到列表中来创建dict,其中键为uid,值为。问题是如果uid再次出现,我如何将其值再次附加到列表中。&因为有很多uid,我无法创建动态列表。这是我的代码
 为fh中的行导入re-dict1={}conid=[]fh=open(“C:\\test”,“r”):if-re.search(“BIND-REQ”,line):conid.append(line.split()[4])dict1[line.split()[-1]。split(,”[0]]=conid fh.close()打印(len(dict1['dn uid=test1']))
打印输出是整个文件中的行数,但我想知道UID的行数。请看我上面发布的代码,我想的是完全相同的行,但不知怎么搞糊涂了。我添加了关于如何向dict添加键和值的说明。你能看一下我上面发布的代码吗?我想的是完全相同的l但不知怎么搞糊涂了。我添加了关于如何在dict中添加键和值的说明。