尝试将字典写入CSV文件时,Str属性没有键

时间:2017-11-22 02:55:10

标签: python csv dictionary

我正在尝试使用以下代码将字典写入CSV文件:

def condense_data(in_file, out_file, city):
"""
This function takes full data from the specified input file
and writes the condensed data to a specified output file. The city
argument determines how the input file will be parsed.

HINT: See the cell below to see how the arguments are structured!
"""

with open(out_file, 'w') as f_out, open(in_file, 'r') as f_in:
    # set up csv DictWriter object - writer requires column names for the
    # first row as the "fieldnames" argument

    out_colnames = ['duration', 'month', 'hour', 'day_of_week', 'user_type']        
    trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames)
    trip_writer.writeheader()

    ## TODO: set up csv DictReader object ##
    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, 'month': month, 'hour': hour,
                     'day_of_week': day_of_week, 'user_type': user_type}



        print(new_point) # Works fine till here, I am able print the right output
        trip_writer.writerows(new_point) # throws an error

以下是引发的错误:

  

AttributeError Traceback(最近一次调用   最后)in()         8         9为city,文件名为city_info.items():   ---> 10个condense_data(文件名[' in_file'],文件名[' out_file'],city)        11 print_first_point(文件名[' out_file'])

     

在condense_data中(in_file,out_file,   市)        38 ##见https://docs.python.org/3/library/csv.html#writer-objects ##        39打印(new_point)   ---> 40 trip_writer.writerows(new_point)        41        42

     写作者中的

/opt/conda/lib/python3.6/csv.py(self,rowdicts)       156       157 def writer(自我,rowdicts):    - > 158 return self.writer.writerows(map(self._dict_to_list,rowdicts))       159       160#Guard Sniffer的类型检查不包括复杂()

的构建      _dict_to_list中的

/opt/conda/lib/python3.6/csv.py(self,rowdict)       146 def _dict_to_list(self,rowdict):       147如果self.extrasaction ==" raise":    - > 148 wrong_fields = rowdict.keys() - self.fieldnames       149 if wrong_fields:       150引发ValueError(" dict包含不在字段名中的字段:"

     

属性错误:' str'对象没有属性'键'

我确实在Stack Overflow上看到了这类问题,但没有一个帮助过。

2 个答案:

答案 0 :(得分:4)

您正在使用writerows()您应该使用writerow()的地方,因为您正试图写一行,而不是一行。

答案 1 :(得分:0)

我一直在尝试这里和任何地方提出的每个解决方案 - 并且仍然不断收到“'str'对象没有属性'keys'”错误。我无法让 writerow(s) 处理我的数据,所以我只是将字典转换为 Pandas 数据框,然后将 pd 数据框导出到 csv。

示例字典:

    {'Time': [1622178352.7355769,1622178356.1456945,1622178358.7532275,1622178361.4067194,1622178393.741893,1622178397.9731262],
   'H': ['HV', 'HV', 'HV', 'HV', 'HV', 'HV'],
   'Horizon_dist': ['14.01', '13.50', '13.50', '13.50', '18.50', '18.50'],
   'Horizon_units': ['F', 'F', 'F', 'F', 'F', 'F'],
   'Azimuth': ['126.20', '129.10', '128.70', '128.80', '109.50', '109.90'],
   'Azimuth_units': ['D', 'D', 'D', 'D', 'D', 'D'],
   'Inclination': ['-0.50', '-0.70', '-1.60', '-1.70', '7.20', '-0.00'],
   'Inclination_units': ['D', 'D', 'D', 'D', 'D', 'D'],
   'Range': ['14.01', '13.50', '13.50', '13.50', '18.50', '18.50'],
   'Range_units': ['F', 'F', 'F', 'F', 'F', 'F'],
   'Tilt': ['48', '46', '41', '4F', '6F', '4B']}

然后转换为熊猫数据框:

df = pd.DataFrame.from_dict(adict)
df.to_csv(r'data.csv', index = False)