从行数据更新 python 中的字典
update dictionary in python from line data
我有一个脚本,我可以在其中逐行读取文件并将一些信息保存到列表和字典中。也就是说,我存储要传递给字典的键(比如 ley1 和 key2)和一个要作为项目存储在字典中的列表。
碰巧我只有在满足某些条件时才必须更新字典,即:
myDict = {}
if mylist:
myDict[key1][key2] = mylist
当然,如果 key2 不存在,这将引发 KeyError。因此,我引入了以下功能:
def updateDict2keys(myDict,mykey1,mykey2,myitems):
"""
updates a dictionary by appending values at given keys (generating key2 if not given)
input: key1, key2 and items to append
output: dictionary orgnanized as {mykey1:{mykey2:myitems}}
"""
try:
myDict[mykey1][mykey2] = myitems
except KeyError:
myDict[mykey1] = {mykey2:myitems}
# output
return myDict
我的问题是:"safe"在主代码中的for循环中调用这样的函数是这样的吗?
with open(os.path.join(path+myfile)) as ntwkf:
# read file
rdlistcsv = csv.reader(ntwkf)
rowslist = [line for line in rdlistcsv]
ntwkJuncDict = {}
for idx,f in enumerate(rowslist): # loop over file lines
if f:
lineelmnt = f[0].split()[0]
else:
continue
# flags
isBranchName = True if lineelmnt=='definitions' else False
isJunction = True if lineelmnt=='connections' else False
# update dictionary
if isBranchName:
reachname = f[0].split()[2].replace("'","")
if isJunction:
usreach = f[0].split()[2].replace("'","")
uschain = float(f[1].replace("'","").replace(" ",""))
if usreach:
uslist = [usreach, uschain]
todivide.append(uslist)
ntwkJuncDict = updateDict2keys(ntwkJuncDict, reachname, 'upstream', uslist)
我必须说,我的代码工作得很好,我只是在问自己(当然还有你们自己!)我是否按照 python 的方式做所有事情,是否有更聪明的解决方案。
不访问主键,而是使用 dict.setdefault
和默认的空 dict
。
def updateDict2keys(myDict,mykey1,mykey2,myitems):
myDict.setdefault(mykey1, {})[mykey2] = myitems
return myDict
请注意,您的初始方法也是安全的。只有查找,而不是赋值,抛出 KeyError
。在语句myDict[mykey1][mykey2] = myitems
中,没有设置KeyError
只能抛出mykey1
。因此,在 KeyError
上将其设置为空 dict
不会覆盖任何内容。
我有一个脚本,我可以在其中逐行读取文件并将一些信息保存到列表和字典中。也就是说,我存储要传递给字典的键(比如 ley1 和 key2)和一个要作为项目存储在字典中的列表。
碰巧我只有在满足某些条件时才必须更新字典,即:
myDict = {}
if mylist:
myDict[key1][key2] = mylist
当然,如果 key2 不存在,这将引发 KeyError。因此,我引入了以下功能:
def updateDict2keys(myDict,mykey1,mykey2,myitems):
"""
updates a dictionary by appending values at given keys (generating key2 if not given)
input: key1, key2 and items to append
output: dictionary orgnanized as {mykey1:{mykey2:myitems}}
"""
try:
myDict[mykey1][mykey2] = myitems
except KeyError:
myDict[mykey1] = {mykey2:myitems}
# output
return myDict
我的问题是:"safe"在主代码中的for循环中调用这样的函数是这样的吗?
with open(os.path.join(path+myfile)) as ntwkf:
# read file
rdlistcsv = csv.reader(ntwkf)
rowslist = [line for line in rdlistcsv]
ntwkJuncDict = {}
for idx,f in enumerate(rowslist): # loop over file lines
if f:
lineelmnt = f[0].split()[0]
else:
continue
# flags
isBranchName = True if lineelmnt=='definitions' else False
isJunction = True if lineelmnt=='connections' else False
# update dictionary
if isBranchName:
reachname = f[0].split()[2].replace("'","")
if isJunction:
usreach = f[0].split()[2].replace("'","")
uschain = float(f[1].replace("'","").replace(" ",""))
if usreach:
uslist = [usreach, uschain]
todivide.append(uslist)
ntwkJuncDict = updateDict2keys(ntwkJuncDict, reachname, 'upstream', uslist)
我必须说,我的代码工作得很好,我只是在问自己(当然还有你们自己!)我是否按照 python 的方式做所有事情,是否有更聪明的解决方案。
不访问主键,而是使用 dict.setdefault
和默认的空 dict
。
def updateDict2keys(myDict,mykey1,mykey2,myitems):
myDict.setdefault(mykey1, {})[mykey2] = myitems
return myDict
请注意,您的初始方法也是安全的。只有查找,而不是赋值,抛出 KeyError
。在语句myDict[mykey1][mykey2] = myitems
中,没有设置KeyError
只能抛出mykey1
。因此,在 KeyError
上将其设置为空 dict
不会覆盖任何内容。