使用DictReader对象

时间:2017-12-22 04:26:55

标签: python csv dictionary

设置上下文我需要根据我的要求转换csv文件,以创建转换后的csv输出文件。

对于这个问题陈述,我了解到我需要使用python csv中的DictReader。转换后,我尝试创建另一个名为new_point的字典,需要将其保存到csv文件中。

问题是,字典生成似乎在我的代码中存在缺陷,因为当我打印字典时,它既不是字典数组也不是字典。

with open(out_file, 'w') as f_out, open(in_file, 'r') as f_in:
        out_colnames = ['duration', 'month', 'hour', 'day_of_week', 'user_type']        
        trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames)
        trip_writer.writeheader()

        trip_reader = csv.DictReader(f_in)

        # collect data from and process each row
        for row in trip_reader:
            # set up a dictionary to hold the values for the cleaned and trimmed
            # data point
            new_point = {}
            ## TODO: use the helper functions to get the cleaned data from  ##
            ## the original data dictionaries.                              ##
            ## Note that the keys for the new_point dictionary should match ##
            ## the column names set in the DictWriter object above.         ##
            duration = duration_in_mins(row, city)
            month,hour,day_of_week = time_of_trip(row, city)
            user_type = type_of_user(row, city)

            new_point['duration'] = duration
            new_point['month'] = month
            new_point['hour'] = hour
            new_point['day_of_week'] = day_of_week
            new_point['user_type'] = user_type

            pprint(new_point)

如果我打印type(new_point)我得到的输出如下

Class <Dict>

当我打印new_point dict时,我得到了以下内容。

{'day_of_week': 'Thursday',
 'duration': 7.123116666666666,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 9.792516666666668,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 6.632983333333333,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 7.4047,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 13.014583333333333,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 17.0552,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 11.01165,
 'hour': 22,
 'month': 3,
 'user_type': 'Registered'}
{'day_of_week': 'Thursday',
 'duration': 30.01175,
 'hour': 21,
 'month': 3,
 'user_type': 'Registered'}

已经按照这种方法从DictReader对象创建字典的人可以帮我解决这个问题。

如果你觉得这个问题很天真,我真诚的道歉。我是python的新手。我尝试阅读文档,但不理解这个概念。我甚至无法在任何地方找到详细的解释。

1 个答案:

答案 0 :(得分:1)

从我看到的情况来看,new_point看起来不错:它是一个字典,其键与列标题相同。但是,我没有看到任何写入输出的语句。如何在构建字典后编写字典?

        new_point['duration'] = duration
        new_point['month'] = month
        new_point['hour'] = hour
        new_point['day_of_week'] = day_of_week
        new_point['user_type'] = user_type
        trip_writer.writerow(new_point)  # Write to the file