如何在Python中的字典中为变量赋值?

时间:2018-03-07 04:41:18

标签: python csv

我正在为一个类项目使用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

1 个答案:

答案 0 :(得分:1)

我相信您对相关代码的缩进是错误的。如果是,请更新。

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: