【发布时间】:2025-11-23 06:20:04
【问题描述】:
我正在为一个班级项目使用 csv。它有 3 列,“year”、“title_field”和“value”。在尝试解决更大的问题时,我只想能够根据年份和标题字段将变量分配给特定值。
csv 看起来像这样:
2008,Total Housing Units,41194
2008,Vacant Housing Units,4483
2008,Occupied Housing Units,36711
这是我的代码:
import csv
ohu = 'Occupied Housing Units'
vhu = 'Vacant Housing Units'
thu = 'Total Housing Units'
filename = 'denton_housing.csv'
# creates dictionary
with open(filename, 'r', encoding='utf8', newline='') as f:
housing_stats = []
for row in csv.DictReader(f, delimiter=','):
year = int(row['year'])
field_name = row['title_field']
value = int(row['value'])
denton_dict = {'year': year, 'title_field': field_name, 'value': value}
housing_stats.append(denton_dict)
if row['year'] == 2008 and row['title_field'] == vhu:
vac_unit = int(row['value'])
print(vac_unit)
我使用 print 语句运行程序,底部没有 if 语句,它给了我整个 csv 数据作为字典列表,这正是我想要的。但是,当我将其更改为现在的样子时,它只是运行并且不打印任何内容。
例如,有一行将匹配年份和特定的标题字段。我正在尝试将该行中的值分配给vac_unit
【问题讨论】:
-
您的代码中存在缩进错误。