gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:34 24 4
gpt4 key购买 nike

我正在尝试使用以下代码将字典写入 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 (most recent call last) in () 8 9 for city, filenames in city_info.items(): ---> 10 condense_data(filenames['in_file'], filenames['out_file'], city) 11 print_first_point(filenames['out_file'])

in condense_data(in_file, out_file, city) 38 ## see https://docs.python.org/3/library/csv.html#writer-objects ## 39 print(new_point) ---> 40 trip_writer.writerows(new_point) 41 42

/opt/conda/lib/python3.6/csv.py in writerows(self, rowdicts) 156 157 def writerows(self, rowdicts): --> 158 return self.writer.writerows(map(self._dict_to_list, rowdicts)) 159 160 # Guard Sniffer's type checking against builds that exclude complex()

/opt/conda/lib/python3.6/csv.py in _dict_to_list(self, rowdict) 146 def _dict_to_list(self, rowdict): 147 if self.extrasaction == "raise": --> 148 wrong_fields = rowdict.keys() - self.fieldnames 149 if wrong_fields: 150 raise ValueError("dict contains fields not in fieldnames: "

AttributeError: 'str' object has no attribute 'keys'

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

最佳答案

您在应该使用 writerow() 的地方使用了 writerows(),因为您正在尝试写入一行,而不是它们的列表。

关于python - 尝试将字典写入 CSV 文件时,Str 属性没有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com