繁体   English   中英

如何将变量分配给 Python 字典中的值?

[英]How can I assign a variable to a value in a dictionary in Python?

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

我使用打印语句运行程序,底部没有 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:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM