我正在为一个班级项目使用csv。它具有3列:“年”,“ title_field”和“值”。在尝试解决更大的问题时,我只希望能够根据年份和标题字段将变量分配给特定值。
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
最佳答案
我认为您缩进相关代码是错误的。如果是,请更新。
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)
您正在将整数与字符串进行比较。
if row['year'] == 2008 and row['title_field'] == vhu:
应该是
if row['year'] == '2008' and row['title_field'] == vhu:
要么
if int(row['year']) == 2008 and row['title_field'] == vhu:
关于python - 如何在Python中的字典中为变量赋值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49144264/