具有元组键和值的Python字典

时间:2013-12-17 19:54:01

标签: python dictionary key tuples

我喜欢的是{(x1,y1):(a1,b1,c1),(x2,y2):(a2,b2,c2),(x3,y3):(a3,b3,c3),...}

格式的字典

所有数据都在文本文件中,格式如下:

x1 y1 a1
...
x1 y1 b1
...
x1 y1 c1
...
x2 y2 a2
...
x2 y2 b2
...
x2 y2 c2 
...

我读了文本文件,但我不知道如何将a,b,c值与相应的键相关联。

我现在的脚本给了我{(x1,y1):c1,(x2,y2):c2,(x3,y3):c3,...}这是不正确的

由于我逐一阅读这些行,我不知道如何保存a,b值。

1 个答案:

答案 0 :(得分:4)

with open('path/to/input') as infile:
    answer = {}
    for line in infile:
        x,y,v = line.split()
        k = (x,y)
        if k not in answer:
            answer[k] = []
        answer[k].append(v)
answer = {k:tuple(v) for k,v in answer.items()}

当然,您可以使用collections.defaultdict来减轻您的负担:

import collections
with open('path/to/input') as infile:
    answer = collections.defaultdict(list)
    for line in infile:
        x,y,v = line.split()
        answer[(x,y)].append(v)
answer = {k:tuple(v) for k,v in answer.items()}