2016-11-07 71 views
0

当将OrderedDict封装到dict中时,会出现OrderedDict未更新的问题。字典中的封装OrderedDict

目的是为了获得与形式的dictonary:

{name1: OrderedDict({year1:amount,year2:amount,...}), name2: OrderedDict({year1:amount,year2:amount,...})} 

但是初始化第一temp_ord后,将不予进一步更新,因此去年金额对可用于每个名称相同第一后。

CSV结构在列中:名称年份编号。我不确定这是一个循环错误,还是因为封装了这些字典。

import csv 
from collections import OrderedDict 

def plot_names(file_name, names): 
    temp_dict = {} 
    temp_ord = OrderedDict({}) 
    with open(file_name) as csvfile: 
     reader = csv.DictReader(csvfile) 
     for name in names: 
      for row in reader: 
       if name == row["name"]: 
        temp_ord[row["year"]] = row["number"] 
      temp_dict[name] = temp_ord 
    return temp_dict 

数据格式:

year name gender number /n 1993 Abarna f 1 /n 1993 Abetare f 1 /n 1993 Abir f 1 
+0

你能显示你的数据吗? –

+0

它已更新。你看到所有的* last *数据,因为它们都引用同一个对象**。 *在循环*内移动'temp_ord = OrderedDict()'(额外的字典是不必要的)*。 – jonrsharpe

+0

@jonrsharpe在哪个循环中,你能提供固定循环吗? – MtSummerbreeze

回答

0

的问题是,读者只能使用一次(感谢@jonrsharpe)消耗。

import csv 
from collections import OrderedDict 

def plot_names(file_name, names): 
    temp_dict = {} 
    for name in names: 
      with open(file_name) as csvfile: 
       reader = csv.DictReader(csvfile) 
       temp_ord = OrderedDict({}) 
       for row in reader: 
        if name == row["name"]: 
         temp_ord[row["year"]] = row["number"] 
       temp_dict[name] = temp_ord 
    return temp_dict