我正在尝试做一些应该非常简单的事情,它只是抓取存储在字典中的值然后将其分配给变量。
current_bytes_total = DPIstats[applicationName]['Total Bytes'] # extract old byte count
这直接在解释器中工作,但是当我尝试在程序中执行此操作时,它会出现以下错误:
"newValue = new_bytes_total + current_bytes_total # add new byte count to old byte count
TypeError:+:'int'和'dict'的不支持的操作数类型“
有没有办法检索存储在字典中的值,以便将其分配给变量?
粘贴所有内容,以防万一我在此之前已经做了一些事情,这阻止了它的工作。
def getFileName(filename):
file_contents = open(filename,'rU')
DPIstats={} # create empty dictionary to hold application name to byte values
for line in file_contents:
values = line.split() # split each line on white space and put each lines values into a list
# print(values)
# uncomment print(values)to test the values in my data structure
if 'End:' in values: # if 'End:' in values then this is an end record
# grab the values in the list for positions [-4] (bytes sent)
# and [-2] (bytes received) and store below
applicationName = values[14] # type is string
if applicationName in DPIstats: # if application name key already exists do nothing
pass
else: # if application name doesn't exist create a new dict entry
DPIstats[applicationName]= {}
DPIstats[applicationName]['Total Bytes'] = {}
bytes_sent = 0
bytes_received = 0
current_bytes_total = 0
new_bytes_total = 0
newValue = 0
bytes_sent += int(values[-4]) # convert to an integer
bytes_received += int(values[-2]) # convert to an integer
new_bytes_total = bytes_sent + bytes_received # get new byte count from current entry
current_bytes_total = DPIstats[applicationName]['Total Bytes'] # extract old byte count
newValue = new_bytes_total + current_bytes_total # add new byte count to old byte count
DPIstats[applicationName]['Total Bytes'] = newValue # assign new value to Total Bytes stored for the application name
file_contents.close() # close the file
def main():
filename = sys.argv[1] # get the first command line argument and assign
getFileName(filename) # call and feed specified filename
if __name__ == '__main__':
main() # call the main function to get things started
提前致谢!!!
答案 0 :(得分:2)
我不知道这是什么语言但是......
DPIstats[applicationName]['Total Bytes'] = {}
...似乎解释了为什么你得到关于TotalBytes是字典的错误。我认为你的意思是{}
为0