Python С;创建多级词典

Python С;创建多级词典,python,Python,我有许多文件的数据组织如下: 20190920;100000;MGNT;3616 20190920;100000;RSTI;10128 20190920;100001;SIBN;4150.5 20190920;100001;SNGSP;3771.5 20190920;100002;MGNT;3617 20190920;100002;TATN;2966.8 20190920;100003;SNGSP;15086 20190920;100004;TATNP;1359.6 20190920;10000

我有许多文件的数据组织如下:

20190920;100000;MGNT;3616
20190920;100000;RSTI;10128
20190920;100001;SIBN;4150.5
20190920;100001;SNGSP;3771.5
20190920;100002;MGNT;3617
20190920;100002;TATN;2966.8
20190920;100003;SNGSP;15086
20190920;100004;TATNP;1359.6
20190920;100005;SNGSP;75410
20190920;100005;AFLT;133672.4
20190920;100005;SNGSP;3771.5
我想读它们并编一本字典。 MGNT、TATN等股票代码是其关键。 它的值类似于字典

{20190920 : value}
其中,值是数字列表:

[3616, 3617 .....] #they are the last digits in my data example. 
所以,这有点像

{'MGNT' : {20190920 : [3616, 3617, 3615]}}
这就是我所做的,没有结果

crude_base = {}
for item in datafiles: #loop throw files. 1 file contains data for 1 day
    # open file
    for line in file_object:    
        line = line.split(';')  
        date = line[0]
        time = line[1]
        ticker = line[2]
        price = line[3]
        #Now I want to append price in list inside crude_base[ticker][data] 

如何在字典中的列表中添加price?

您可能需要检查键是否存在,如下所示:

crude_base = {}
for item in datafiles: #loop throw files. 1 file contains data for 1 day
    # open file
    for line in file_object:    
        line = line.split(';')  
        date = line[0]
        time = line[1]
        ticker = line[2]
        price = line[3]
        if ticker not in crude_base:
            # Create the first level with a dictionary
            crude_base[ticker] = {date: [price]}
        else:
            # crude_base[ticker] exists and is a dictionary
            if date in crude_base[ticker]:
                # Date list already exists, just add the price to the list
                crude_base[ticker][date].append(price)
            else:
                # Create the dictionary entry for this date
                crude_base[ticker][date] = [price]

假设你不在乎节省时间,这应该是你想要的

rough_base={}
对于数据文件中的项目:
#打开文件
对于文件\u对象中的行:
line=line.split(“;”)
日期=第[0]行
时间=行[1]
股票代码=第[2]行
价格=行[3]
如果股票代码不在原油基础上:
粗碱[ticker]={}
如果日期不在原油基础上[ticker]:
原油基数[股票代码][日期]=[价格]
其他:
原油基数[股票代码][日期].追加(价格)

您可以使用defaultdict,它将为您构建字典,而无需定义键

使用此选项,您可以使用列表的值定义嵌套在另一个字典中的字典。当您使用roud_base[ticker][date]引用时,会自动创建一个空列表(或您指定的任何项目,例如,您可以指定一个集合或int等)

然后代码看起来像

from collections import defaultdict


crude_base = defaultdict(lambda: defaultdict(list))

# 1. loop thought the files
for item in datafiles:

    # 2. open file
    for line in file_object: 

        # 3. Unpack into parts
        date, time, ticker, price = line.split(';')

        # 4. Append price in list inside crude_base[ticker][date]
        crude_base[ticker][date].append(price)


在我看来,它就像是从
行中得到的列表。split
的长度应该是4,但在您的示例中,您将price设置为
行[2]
。是不是应该是
3
,还是我遗漏了什么?谢谢。我现在就更正。如果我没有弄错的话,在您的示例中,第一个
价格
被添加了两次,倒数第二行应该有一个
else