读取CSV文件并附加到字典

时间:2014-04-17 03:06:50

标签: python csv

请如何循环csv文件RESULT4中的所有行,然后检查元组BR的列表,以查看每个元组中的第一个和第二个元素是否分别与NodeA和NodeB列中的值匹配并添加LOAD列中的相应值如果匹配则进入BR中的字典元素。谢谢

RESULT4.csv = Link  NodeA   NodeB   LOAD
               4    71001   8427    961.325492
               6    71002   71009   17.302306
              12    71004   8430    0.642499
              15    71003   8429    3.685375
              16    71006   8833    1.291624
              18    71007   71008   6.536354
              20    71009   70514   65.200511


BR = [(71001, 8427,{'lanes': 9, 'length': 0.1,}),(71003, 8429,{'lanes': 9, 'length': 0.8,}),(71007, 71008,{'lanes': 6, 'length': 0.3,}), (7100, 7104,{'lanes': 6, 'length': 0.3,})]

我尝试了这个,但我没有得到理想的结果。

with open('RESULT4.csv', 'rb') as f:
    reader = csv.reader(f)
        for row in reader:
            if (BR[0][0]).find(row[1]) and (BR[0][1]).find(row[2]):
            BR[0][2]['volume'] = str(row[3])
print BR

输出应如此:

BR = [(71001, 8427,{'volume': 961.325492, 'lanes': 9, 'length': 0.1,}),(71003, 8429,{'volume': 3.685375,'lanes': 9, 'length': 0.8,}),(71007, 71008,{'volume': 6.536354,'lanes': 6, 'length': 0.3,}), (7100, 7104,{'lanes': 6, 'length': 0.3,})]

1 个答案:

答案 0 :(得分:1)

主要是您的算法失败,因为您在元组列表中省略了第二个循环。

使用此csv文件:

Link,NodeA,NodeB,LOAD
4,71001,8427,961.325492
6,71002,71009,17.302306
12,71004,8430,0.642499
15,71003,8429,3.685375
16,71006,8833,1.291624
18,71007,71008,6.536354
20,71009,70514,65.200511

和此代码

import csv

BR = [(71001, 8427,{'lanes': 9, 'length': 0.1,}),
        (71003, 8429,{'lanes': 9, 'length': 0.8,}),
        (71007, 71008,{'lanes': 6, 'length': 0.3,}), 
        (7100, 7104,{'lanes': 6, 'length': 0.3,})]

with open('result4.csv') as f:
        for row in csv.DictReader(f):
            for nodeA, nodeB, attrDict in BR:
                if nodeA == int(row['NodeA']) and nodeB == int(row['NodeB']):
                    attrDict.update({'volume' : str(row['LOAD'])})
print BR

我获得了这个输出:

[(71001, 8427, {'volume': '961.325492', 'length': 0.1, 'lanes': 9}), 
 (71003, 8429, {'volume': '3.685375', 'length': 0.8, 'lanes': 9}), 
 (71007, 71008, {'volume': '6.536354', 'length': 0.3, 'lanes': 6}), 
 (7100, 7104, {'length': 0.3, 'lanes': 6})]

我希望这可以帮到你。