追加或新建词典

2024-04-25 21:21:31 发布

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

我有两个文件,一个只有Keys,另一个有Key and Value。我试图用相应的值附加键文件,或者用键和相应的值创建一个新的输出文件。我个人能很好地读懂钥匙和价值观。我很难把两者结合起来。下面的代码显示了最终值。我知道第一个for循环结束,第二个for循环开始。这就是为什么我只从键和值文件中获取最后一项。如何用简单的方法解决这个问题?你知道吗

from collections import defaultdict

with open('input1', 'r') as classified_data:
    with open('input2', 'r') as edge_data:    
        with open('output', 'w') as outfile:  
        for row in classified_data:
            col = row.strip().split()
            key = col[0], col[1]
            #print key
        for row in edge_data:
            col = row.strip().split()           
            value = col[2], col[3], col[4]
            #print value
        print {key:value}

输入1:

3545 4945
3545 2814
3545 5045
3545 4921
3545 2564
3545 2311
3545 1644
3545 3820
3545 388
3545 928
3545 3626
3545 1191
3545 4243
3545 3867
3545 701

输入2:

4945 3545 57 250848.0 4400.84210526 
3584 292 5 1645.0 329.0 
4824 2283 5 16867.0 3373.4 
1715 55 1 681.0 681.0 
5409 2822 2 3221.0 1610.5 
4955 656 6 3348.0 558.0 
4157 487 1 201.0 201.0 
2628 309 2 2466.0 1233.0 
3929 300 2 1742.0 871.0 
3730 489 12 10706.0 892.166666667 
5474 2336 2 1533.0 766.5 
3877 716 10 45028.0 4502.8 
3058 3045 12 17328.0 1444.0 

Tags: 文件keyinfordatavalueaswith
2条回答

在我看来,您似乎想使用从第一个文件获得的密钥,对第二个文件中的数据进行多次查找。如果是这种情况,并且假设您可以将第二个文件放入内存中,那么我建议将第二个文件读入一个字典,其中包含用于查找的键:

edges = {}
with open('input2', 'r') as edge_data:    
    for row in edge_data:
        col = row.strip().split()
        edges[col[0], col[1]] = col[2], col[3], col[4]

然后要进行查询,请通读第一个文件并打印出匹配项:

with open('input1', 'r') as classified_data:
    for row in classified_data:
        key = tuple(row.strip().split())
        print key, edges.get(key)

如果要根据数字的任意顺序匹配键,则可以修改最后一段代码以显式尝试这两种组合:

with open('input1', 'r') as classified_data:
    for row in classified_data:
        a, b = row.strip().split()
        print a, b, edges.get((a, b), edges.get((b, a)))

如何收集元组列表中的键和值,最后将它们压缩到dict中?你知道吗

from collections import defaultdict

keys = []
values = []

with open('input1', 'r') as classified_data:
    # with open('output', 'w') as outfile:  
    for row in classified_data:
        col = row.strip().split()
        keys.append((col[0], col[1]))
        # print key
with open('input2', 'r') as edge_data:    
    for row in edge_data:
        col = row.strip().split()           
        values.append((col[2], col[3], col[4]))
        # print value

print dict(zip(keys,values))

相关问题 更多 >