如何将从python字典中检索到的值赋给变量?

2024-04-20 12:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一些非常简单的事情,就是抓取一个存储在字典中的值,然后把它赋给一个变量。你知道吗

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

提前谢谢!!!你知道吗


Tags: thetoinnewifbytescountbyte
1条回答
网友
1楼 · 发布于 2024-04-20 12:46:20

我不知道这是什么语言,但是。。。你知道吗

DPIstats[applicationName]['Total Bytes'] = {}

。。。似乎可以解释为什么TotalBytes作为字典会出错。我想你的意思是{}变成0

相关问题 更多 >