嵌套字典会覆盖数据

时间:2017-12-01 00:13:37

标签: python dictionary

我正在尝试从包含以下行的数据文件中读取:

2007 ANDREA 30 31.40 -71.90 05/13/18Z 25 1007 LOW

2007 ANDREA 31 31.80 -69.40 05/14/00Z 25 1007 LOW

我正在尝试创建一个嵌套字典,其中包含一个持有年份的键,然后嵌套字典将包含名称和包含统计信息的元组。我希望返回值看起来像这样:

{'2007': {'ANDREA': [(31.4, -71.9, '05/13/18Z', 25.0, 1007.0), (31.8, -69.4, '05/14/00Z', 25.0, 1007.0)] 

但是,当我运行代码时,它只返回一组统计信息。它似乎覆盖了自己,因为我正在返回txt文件中的最后一行统计信息:

{'2007': {'ANDREA': [(31.8, -69.4, '05/14/00Z', 25.0, 1007.0)]

以下是代码:

def create_dictionary(fp):
'''Remember to put a docstring here'''
   dict1 = {}
   f = []
   for line in fp:
       a = line.split()
       f.append(a)
   for item in f:
       a = (float(item[3]), float(item[4]), item[5], float(item[6]), 
   float(item[7]))

       dict1 = update_dictionary(dict1, item[0], item[1], a))                                        

   print(dict1)

def update_dictionary(dictionary, year, hurricane_name, data):

   if year not in dictionary:
        dictionary[year] = {}

        if hurricane_name not in dictionary:
            dictionary[year][hurricane_name] = [data]

        else:
            dictionary[year][hurricane_name].append(data)      

    else:    
        if hurricane_name not in dictionary:
            dictionary[year][hurricane_name] = [data]

        else:
            dictionary[year][hurricane_name].append(data)

    return dictionary  

2 个答案:

答案 0 :(得分:0)

这些行:

    if hurricane_name not in dictionary:

......应该是:

    if hurricane_name not in dictionary[year]:

答案 1 :(得分:0)

因为我有点迟到这是一个建议,而不是你原来问题的答案。您可以稍微简化逻辑,因为当年份不存在时,该年份的名称也不存在。所有内容都可以放在一个函数中,使用“with”语句打开文件将确保即使程序遇到错误也能正常关闭。

def build_dict(file_path):

    result = {}

    with open(file_path, 'r') as f:

        for line in f:

            items = line.split()

            year, name, data = items[0], items[1], tuple(items[2:])

            if year in result:

                if name in result[year]:

                    result[year][name].append(data)

                else:

                    result[year][name] = [data]

            else:

                result[year] = {name: [data]}

    return result


print(build_dict(file_path))

输出:

{'2007': {'ANDREA': [('30', '31.40', '-71.90', '05/13/18Z', '25', '1007', 'LOW'), ('31', '31.80', '-69.40', '05/14/00Z', '25', '1007', 'LOW')]}}