使用字典构建数据

时间:2018-01-17 17:55:20

标签: python-2.7 dictionary

我是python的新手,我仍在学习它是如何工作的。距离我开始只有一周了。 我正在尝试编写一个执行此操作的程序:

  1. 从文件中读取4列(上面的ref输入文件)
  2. 从文件中获取日期,日期和计数
  3. 并构建一个字典来表示日期和计数。
  4. 基本上我想用下面的代码表示数据,我被困在语法中。

    {
     "xyz" : 
        {"Sunday" :     {
                    "20180101" : 72326, 
                    "20180108" : 71120
                    }
        "Monday" :                  {
                    "20171225" : 51954, 
                    "20180102" : 51954
                    }
        }       
    }
    
    
    INPUT FILE:
    DateDay             value       count   floatex
    20171225Monday   |    270613|     51954|11.41|
    20171226Tuesday  |    133579|     46126|12.01|
    20171227Wednesday|    630613|     71954|11.41|
    20171228Thursday |    253779|     96126|12.01|
    20171229Friday   |    688613|     71054|11.41|
    20171230Saturday |    633779|     66126|12.01|
    20180101Sunday   |    633779|     72326|12.01|
    20180102Monday   |    630613|     91954|11.41|
    20180103Tuesday  |    538779|     73326|12.01|
    20180104Wednesday|    630613|     61954|11.41|
    20180105Thursday |    393379|     75146|12.01|
    20180106Friday   |    130613|     51954|11.41|
    20180107Saturday |   2643329|     70126|12.01|
    20180108Sunday   |    863979|     71120|12.01|
    

    这就是我所拥有的,但它远非我想要的东西:现在它的抛出错误..但这不是我的问题。基本上我想了解如何根据输入数据创建嵌套字典

    def buildInputDataDictionary(file, ind):
    dateCount = {}
    dateDay = {}
    
    #dictData = {}
    #   dateCount[dictData] = {}
    with open(file) as f:
        for line in f:
            items = line.split("|")
            date=items[0].strip()[0:8]          ##strip spaces and substring to get only the date
            count= items[2].strip()
            day= items[0].strip()[8:]   
            dateCount[date] = count
            dateDay[date] = day
            dictData = {}
            dictData[date] = {}
            dictData [ind][date] = count
    
    return dateCount,dateDay,dictData
    
    dc,dd, di= buildInputDataDictionary(autoInqRhf, "xyz")          
    
    print dd
    print dc
    print di
    

1 个答案:

答案 0 :(得分:0)

在当前脚本中,您将在每个for循环中重置字典。您只需要在循环外启动它一次。添加嵌套数据时,您必须确保所有要输入的键都已存在。你可以这样做

#initate dictionary with your identifier as first object
dictData = {ind: dict()}

with open(file) as f:
    for line in f:
        # extact your data (haven't tested your code)
        items = line.split("|")
        day = items[0].strip()[0:8]
        date = items[0].strip()[0:8]
        count = items[2].strip()

        # add days
        if not day in dictData[ind].keys():
            dictData[ind][day] = dict()

        dictData[ind][day][date] = count