迭代字典时重复键值

时间:2017-09-29 02:50:54

标签: python python-2.7 dictionary

对于下面的代码,我观察到键值(128)被另一个(1280)值重复和覆盖。

代码段:

tput = OrderedDict([('1518',0),('1280',0),('1024',0),('512',0),('256',0),('128',0),('64',0)])



with open(freader) as fcsv:
            reader = csv.reader(fcsv)
            for row in reader:
                if row:
                    for key, value in tput.iteritems():
                        if re.match(key, str(row[0])) and int(row[1]) == 1:
                            tput[key] = row[7]
                            print " key is ", key, " and value is", tput[key]

输入CSV文件包含:

128, 1, 30.0140001774, 177901, 182170952, 100069.492703, 100021.989147, 102422516.887, 1796.00610211, 102423335.704
128, 2, 29.9990000725, 177901, 182170952, 111188.325226, 111576.811204, 114254654.673, 1751.27129964, 113799884.726
128, 3, 29.9839999676, 177901, 182170952, 111188.325226, 111129.135927, 113796235.189, 1737.77562216, 113799885.63
512, 1, 29.9990000725, 75851, 310689185, 71111.1111111, 71085.2360028, 291165126.667, 1757.00878208, 291280637.718
512, 2, 29.9989998341, 75851, 310689185, 71111.1111111, 71111.7041168, 291273540.062, 1842.45717257, 291280640.032
512, 3, 30.013999939, 75851, 310689185, 71111.1111111, 71071.7000179, 291109683.273, 1825.21859093, 291135066.628
1280, 1, 30.013999939, 34441, 352677802, 36593.7661443, 31965.1829796, 327323473.712, 944.594757643, 327323473.712
1280, 2, 30.0140001774, 34441, 352677802, 36593.7661443, 31917.3050689, 326833203.906, 936.91688291, 326833203.906
1280, 3, 29.9979999065, 34441, 352677802, 36593.7661443, 31941.9962326, 327086041.422, 927.958137658, 327086041.422
1518, 1, 30.013999939, 29010, 352303919, 29010.5335866, 26742.8533895, 324765211.562, 770.532335849, 324765211.562
1518, 2, 29.9979999065, 29010, 352303919, 29010.5335866, 26674.55193, 323935758.638, 800.026664257, 323935758.638
1518, 3, 30.013999939, 29010, 352303919, 29010.5335866, 26822.7885119, 325735943.689, 772.290818704, 325735943.689

观察到的输出:

 key is  128  and value is  102422516.887
 key is  512  and value is  291165126.667
 key is  1280  and value is  327323473.712
 key is  128  and value is  327323473.712    --> key 128 again overrides 1280 value
 key is  1518  and value is  324765211.562

我觉得我正在进行标准迭代 - 无法弄清楚我到底做错了什么。

1 个答案:

答案 0 :(得分:1)

$ ./bin/multiply Enter a number: 8 Enter one more number: 7 The result of 8 * 7 is 56 匹配字符串开头的模式。 因此re.match(pattern, string)返回一个真实的匹配器对象。

为什么不直接比较平等:

re.match('128', '1280')

或者根本不要遍历dict,但要检查密钥:

if key == str(row[0]) and ...