python - 同时操作字典中键的两个值

标签 python dictionary

我正在读取以下格式的文件:

0.012281001     00:1c:c4:c2:1f:fe       1    30
0.012285001     00:1c:c4:c2:1f:fe       3    40
0.012288001     00:1c:c4:c2:1f:fe       2    50
0.012292001     00:1c:c4:c2:1f:fe       4    60
0.012295001     24:1c:c4:c2:2f:ce       5    70  

我打算将第 2 列实体作为键,将第 3 列和第 4 列作为单独的值。对于我遇到的每一行,对于该特定键,它们各自的值必须相加(值 1 和值 2 应针对该键单独聚合)。在上面提到的示例中,我需要获得如下输出:

'00:1c:c4:c2:1f:fe': 10 : 180, '24:1c:c4:c2:2f:ce': 5 : 70  

我为简单的1键1值编写的程序如下:

#!/usr/bin/python

import collections
result = collections.defaultdict(int)
clienthash = dict()

with open("luawrite", "r") as f:
    for line in f:
            hashes = line.split()
            ckey = hashes[1]
            val1 = float(hashes[2])
            result[ckey] += val1
    print result  

如何将其扩展为 2 个值以及如何将它们打印为上述输出。我没有得到任何想法。请帮忙!顺便说一句,我正在使用 python2.6

最佳答案

您可以将所有值存储在一个字典中,使用元组作为存储值:

with open("luawrite", "r") as f:
    for line in f:
        hashes = line.split()
        ckey = hashes[1]
        val1 = int(hashes[2])
        val2 = int(hashes[3])
        a,b = result[ckey] 
        result[ckey] = (a+val1, b+val2) 
print result  

关于python - 同时操作字典中键的两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17180193/

相关文章:

python - 登录 python + mod_wsgi 应用程序

python - 如何强制 SAS 等待命令完全执行?

python - Yahoo BOSS V2授权麻烦

C# MVC-发布一个包含字典的 View 模型

python - 打印矩阵的元素,每行另起一行,每行元素之间用空格分隔

python - 一种将非常大的 csv 数据写入 SQL 数据库的方法

python - 如何将字符串 append 到字典中的列表

swift - 遍历字典并创建对象实例

python - .get 和字典

python - 删除键时字典中的键错误