使用csv在python中嵌套字典,我需要减少或增加日期

时间:2018-03-09 00:43:05

标签: python loops csv dictionary

我很兴奋因为我得到了一些朋友的一些提示。我试图使用循环创建字典字典。与我合作的csv的日期是2008年至2014年,我使用日期作为关键。 csv看起来像这样:
年,title_field,值

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

这是我的代码:

import csv

denton_housing = {}
filename = 'denton_housing.csv'
key = 2014

with open(filename, 'r', encoding='utf8', newline='') as f:
    for row in csv.DictReader(f, delimiter=','):
        while key not in denton_housing:
            denton_housing[key] = {}
            denton_housing[key][row['title_field']] = int(row['value'])
            key-1

当我打印出来时,我得到:

{2014: {'Total Housing Units': 49109}}

哪个太棒了!但我需要这个:

{2014: {'Total Housing Units': 49109}, {'Vacant Housing Units': 2814}, \    {'Occupied Housing Units': 46295}}

更重要的是,我需要它回顾并在2013年,2012年,2011年,2010年,2009年和2008年做同样的事情,但要停在那里。

3 个答案:

答案 0 :(得分:4)

您可以使用itertools.groupby创建一个字典,其中每个键都是一年,使用Total Housing UnitsVacant Housing Units存储字典:

import itertools
import csv
with open('filename.csv') as f:
   data = [[int(a), b, int(c)] for a, b, c in sorted(list(csv.reader(f))[1:], key=lambda x:int(x[0]))]

final_data = {a:dict(i[1:] for i in b) for a, b in itertools.groupby(data, key=lambda x:x[0])}

输出:

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

答案 1 :(得分:1)

这里的诀窍是你不希望每个值都有<div>,你需要axios .get(`https://images-api.nasa.gov/search?q=` + `search`) .then(res => res.data.collection.items) .then(json => { json.map(obj => this.setState({ allTheValues: Object.values(obj) })) }) render() {return (<div>{this.state.allTheValues.map(value => value)}</div>)} dict。 (实际上,如果您想要指定的确切输出,list,但我认为您对dict感到满意。)

所以,而不是:

tuple

......这样做:

list

现在,而不是设置

而不是这个:

denton_housing[key] = {}

......这样做:

denton_housing[key] = []

另外,第二部分总是,而不仅仅是denton_housing[key][row['title_field']] = int(row['value']) 。 (另外,您可能需要new_dict = {} new_dict[row['title_field']] = int(row['value']) denton_housing[key].append(new_dict) ,而不是key not in。)

你可以从这里简化一些事情,并建立一个更好的数据结构(你有三个单键词;不是一个dict,多个键更好吗?),等等。但希望这对你来说很容易理解,所以你会被解雇,并且可以从那里疯狂。

答案 2 :(得分:0)

In[2]: import csv
  ...: from collections import defaultdict
  ...: 
  ...: denton_housing = defaultdict(dict)
  ...: filename = 'denton_housing.csv'
  ...: key = 2014
  ...: 
  ...: with open(filename, 'r', encoding='utf8', newline='') as f:
  ...:     for row in csv.DictReader(f):
  ...:         denton_housing[row['year']].update({
  ...:             row['title_field']: int(row['value'])
  ...:         })
  ...: 
In[3]: import json
In[4]: print(json.dumps(denton_housing, indent=4))
{
    "2014": {
        "Total Housing Units": 49109,
        "Vacant Housing Units": 2814,
        "Occupied Housing Units": 46295
    },
    "2013": {
        "Total Housing Units": 47888,
        "Vacant Housing Units": 4215,
        "Occupied Housing Units": 43673
    },
    "2012": {
        "Total Housing Units": 45121,
        "Vacant Housing Units": 3013,
        "Occupied Housing Units": 42108
    },
    "2011": {
        "Total Housing Units": 44917,
        "Vacant Housing Units": 4213,
        "Occupied Housing Units": 40704
    },
    "2010": {
        "Total Housing Units": 44642,
        "Vacant Housing Units": 3635,
        "Occupied Housing Units": 41007
    },
    "2009": {
        "Total Housing Units": 39499,
        "Vacant Housing Units": 3583,
        "Occupied Housing Units": 35916
    },
    "2008": {
        "Total Housing Units": 41194,
        "Vacant Housing Units": 4483,
        "Occupied Housing Units": 36711
    }
}