尝试从嵌套字典中打印百分比

时间:2018-03-09 04:30:51

标签: python csv dictionary floor

我有一个解决这个问题的方法,但是我已经创建了一个应该工作的简约代码,但它并不是。我说"应该"因为当我使用我划分的代码部分,乘以100,并使用我的旧代码使用"{0:.0f}%打印时,它可以工作。但是,我想我已经尝试过过于概念化的东西

import csv, itertools
from math import floor
filename = 'denton_housing.csv'
denton_housing = {}

def create_nested_housing_dict():
    with open(filename, 'r', encoding='utf8', newline='') as f:
        for row in csv.DictReader(f, delimiter=','):
            try:
                denton_housing[row['year']][row['title_field']] = int(row['value'])
            except KeyError:
                denton_housing[row['year']] = {}
    return denton_housing

data = create_nested_housing_dict()


for key, value in data.items():
    print(key + '         ' + "{0:.0f}%".format(int(value['Vacant Housing Units'])) / \
        int(value['Total Housing Units']) * 100 + key + '         ' + \
        "{0:.0f}%".format(int(value['Occupied Housing Units'])) / \
        int(value['Total Housing Units']) * 100)

这一切都给了我这个:

Traceback (most recent call last):
  File "Dictest.py", line 37, in <module>
    int(value['Total Housing Units']) * 100 + key + '         ' + \
KeyError: 'Total Housing Units'

这是我的csv:

year,title_field,value
2014,Total Housing Units,49109
2014,Vacant Housing Units,2814
2014,Occupied Housing Units,46295
2013,Total Housing Units,47888
2013,Vacant Housing Units,4215
2013,Occupied Housing Units,43673
2012,Total Housing Units,45121
2012,Vacant Housing Units,3013
2012,Occupied Housing Units,42108
2011,Total Housing Units,44917
2011,Vacant Housing Units,4213
2011,Occupied Housing Units,40704
2010,Total Housing Units,44642
2010,Vacant Housing Units,3635
2010,Occupied Housing Units,41007
2009,Total Housing Units,39499
2009,Vacant Housing Units,3583
2009,Occupied Housing Units,35916
2008,Total Housing Units,41194
2008,Vacant Housing Units,4483
2008,Occupied Housing Units,36711

2 个答案:

答案 0 :(得分:1)

这应该有所帮助。密钥Key Field1 Created_date 1234 b Feb-18 4567 d Mar-18 未存储在您的'Total Housing Units'词典中。

演示

'denton_housing'

答案 1 :(得分:0)

检查数据字典后,我发现:

Key: 2014
Value: {'Vacant Housing Units': 2814, 'Occupied Housing Units': 46295}
Key: 2008
Value: {'Vacant Housing Units': 4483, 'Occupied Housing Units': 36711}
Key: 2009
Value: {'Vacant Housing Units': 3583, 'Occupied Housing Units': 35916}
Key: 2011
Value: {'Vacant Housing Units': 4213, 'Occupied Housing Units': 40704}
Key: 2010
Value: {'Vacant Housing Units': 3635, 'Occupied Housing Units': 41007}
Key: 2013
Value: {'Vacant Housing Units': 4215, 'Occupied Housing Units': 43673}
Key: 2012
Value: {'Vacant Housing Units': 3013, 'Occupied Housing Units': 42108}

这种情况正在发生,因为“总住房单位”是每年的第一行。
因此,try块失败,并且“ Total Housing Units ”未添加到字典中 但是,对于“空置住房单元”和“被占用住房单元”,尝试块可以顺利运行,并且数据会添加到字典中。