将值附加到字典项

时间:2013-06-28 22:45:46

标签: python

我在我的计划中所做的是:

1. Reading an input file which has 4 columns(All are strings except first column)
2. Splitting them into 4 fields using split()
3. Making last column values as keys and second column values as values
4. If a key already exists, appending the value to the existing item  

示例输入文件是:

66.518706001    00:27:10:2b:93:84       ff:ff:ff:ff:ff:ff       gsdtestopen
72.753800001    00:27:10:2b:93:84       ff:ff:ff:ff:ff:ff       gsdtestopen
90.646014001    00:13:e0:d8:c5:42       ff:ff:ff:ff:ff:ff       alpha_phone
90.646018001    00:13:e0:d8:c5:42       ff:ff:ff:ff:ff:ff       alpha_phone  

我的代码如下:

ssid = dict()
with open("luawrite", "r") as f:
    for line in f:
            hashes = line.split("\t")
            if(hashes[3] != ""):
                    emp = hashes[3]
                    if emp in ssid.keys():
                            ssid[emp].append(hashes[1])
                    else:
                            ssid[emp] = hashes[1]
    print ssid
f.close()  

运行此代码时出现的错误是:

Traceback (most recent call last):
File "ssidcategorize.py", line 10, in <module>
ssid[emp].append(hashes[1])
AttributeError: 'str' object has no attribute 'append'  

我知道我不能追加字符串,但这个问题没有解决?

1 个答案:

答案 0 :(得分:1)

将每个值改为列表(或其他多值类型)。

else:
    ssid[emp] = [hashes[1]]

...

    ssid[emp].add(hashes[1])
else:
    ssid[emp] = set([hashes[1]])