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

Posted

技术标签:

【中文标题】尝试将字典写入 CSV 文件时,Str 属性没有键【英文标题】:Str Attribute has no keys when trying to write dictionary to a CSV file 【发布时间】:2018-05-05 16:23:00 【问题描述】:

我正在尝试使用以下代码将字典写入 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(最近调用 最后)在() 8 9 代表城市,city_info.items() 中的文件名: ---> 10 condense_data(文件名['in_file'],文件名['out_file'],城市) 11 print_first_point(文件名['out_file'])

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

/opt/conda/lib/python3.6/csv.py in writerows(self, rowdicts) 156 157 def writer(自我,rowdicts): --> 158 返回 self.writer.writerows(map(self._dict_to_list, rowdicts)) 159 160 # Guard Sniffer 对排除 complex() 的构建进行类型检查

/opt/conda/lib/python3.6/csv.py in _dict_to_list(self, rowdict) 146 def_dict_to_list(自我,行字典): 147如果self.extrasaction ==“提高”: --> 148 wrong_fields = rowdict.keys() - self.fieldnames 149 如果错误字段: 150 raise ValueError("dict 包含不在字段名中的字段:"

AttributeError: 'str' 对象没有属性 'keys'

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

【问题讨论】:

【参考方案1】:

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

【讨论】:

非常感谢,我不敢相信我错过了。我浏览了 10 次文档 在写字典而不是字典列表时发生在我身上。我切换到for key in maindict: writerow(maindict[key])【参考方案2】:

我一直在尝试这里和任何地方提出的所有解决方案 - 并且仍然不断收到“'str' object has no attribute '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']

然后转换为 pandas 数据框:

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

【讨论】:

以上是关于尝试将字典写入 CSV 文件时,Str 属性没有键的主要内容,如果未能解决你的问题,请参考以下文章

从每个键具有多个值的字典中将数据写入 csv

Python将csv写入字典列表,其中标题作为键,行作为值

Python csv文件到数据字典多个键

将字典列表写入 CSV Python

Python - 需要帮助将字典字典写入 CSV 文件

如何将带有嵌套字典的列表写入 csv 文件?