循环两次后创建新字典

时间:2014-01-26 22:02:15

标签: python for-loop dictionary

我正在尝试清理csv文件的内容,然后从中创建一个新的字典。我希望新词典可以在全球范围内使用:

import csv

input_file = csv.DictReader(open("test_file3.csv"))

final_dict = {} #this should get filled with the new dictionary

for row in input_file: #cleaning the dictionary

    new_dict = {}

    for key, value in row.items():
        if key == "Start Date":
            new_dict[key] = value
        else:
            first_replace = value.replace(".", "")
            second_replace = first_replace.replace(",", ".")
            all_replaced = second_replace.replace(" €", "")
            new_dict[key] = all_replaced

它在第一个循环内部工作,但我不知道如何将new_dict下的字典改为final_dict

理想情况下,我想要final_dict = new_dict。

1 个答案:

答案 0 :(得分:1)

您无需在new_dict循环中创建for,只需访问其中的final_dict

final_dict = {}

for row in input_file:

    for key, value in row.items():
        if key == "Start Date":
            final_dict[key] = value
        else:
            first_replace = value.replace(".", "")
            second_replace = first_replace.replace(",", ".")
            all_replaced = second_replace.replace(" €", "")
            final_dict[key] = all_replaced

 print final_dict

如果有多个条目具有相同的key,则只有最后一个条目将包含在final_dict中。