Python 3中的嵌套Dicts

时间:2017-02-26 13:27:29

标签: python-3.x dictionary

我有一个读取

的文本文件(traders.txt)
    Trade 14: 10000.0 (10000.0) of EUR_USD @ 1.07139
    Trade 15: 10000.0 (10000.0) of AUD_USD @ 0.76
    ================================================

    Trade ID = 14
    Instrument = EUR_USD
    Fill Price = 1.07139
    Open Time = 2017-01-23T13:12:00.587829255Z
    State = OPEN
    Initial Trade Units = 10000.0
    Current Open Trade Units = 10000.0
    Realized Profit/Loss = 0.0
    Unrealized Profit/Loss = -205.45
    Financing = -8.4385

    Trade ID = 15
    Instrument = AUD_USD
    Fill Price = 76.00
    Open Time = 2017-01-23T13:12:00.587829255Z
    State = OPEN
    Initial Trade Units = 10000.0
    Current Open Trade Units = 10000.0
    Realized Profit/Loss = 0.0
    Unrealized Profit/Loss = -105.45
    Financing = -4.4385

我想做的是创建一个与每个段落创建的字典嵌套的字典,以及要从工具中标记的嵌套字典

    IE newdict['AUD_USD']['Trade ID'] to return 15
    and newdict['EUR_USD']['State'] to return OPEN

到目前为止,我已经删除了不需要的前几行,但我不确定如何分离dictionarys

myfile = open('traders.txt', 'r')
newDict = {}
for line in myfile:
    if line in ['\n','\r\n']:
        break
for line in myfile:
    with open("tradersddd.txt", "a") as fout:
         fout.writelines(line)
    listedline = line.strip().split('=') # split around the = sign
    if len(listedline) > 1:
        newDict[listedline[0].strip()] = listedline[1].strip()
print(newDict)

1 个答案:

答案 0 :(得分:0)

以下应该达到你想要的效果。

from itertools import islice
from pprint import pprint

res_dct = {}
with open('traders.txt', 'r') as fin:
    d = {}
    # using islice to cleanly skip over first 4 lines
    for line in islice(fin, 4, None):
        line = line.strip()
        # If line is not empty then add contents to dict
        if line:
            k, v = map(str.strip, line.split(' = '))
            d[k] = v
        # If line is empty then add paragraph to res_dct
        # and re-assign d to a new dict
        else:
            res_dct[d['Instrument']] = d
            # If you don't want Instrument to be in the inner dictionary 
            # use the commented line below instead,
            #res_dct[d.pop('Instrument')] = d 
            d = {}
    # If the file ends and there is data in the dict
    # add it to res_dict
    else:
        if d:
            res_dct[d['Instrument']] = d
            #res_dct[d.pop('Instrument')] = d 

pprint(res_dct)
# Output
{'AUD_USD': {'Current Open Trade Units': '10000.0',
             'Fill Price': '76.00',
             'Financing': '-4.4385',
             'Initial Trade Units': '10000.0',
             'Instrument': 'AUD_USD',
             'Open Time': '2017-01-23T13:12:00.587829255Z',
             'Realized Profit/Loss': '0.0',
             'State': 'OPEN',
             'Trade ID': '15',
             'Unrealized Profit/Loss': '-105.45'},
 'EUR_USD': {'Current Open Trade Units': '10000.0',
             'Fill Price': '1.07139',
             'Financing': '-8.4385',
             'Initial Trade Units': '10000.0',
             'Instrument': 'EUR_USD',
             'Open Time': '2017-01-23T13:12:00.587829255Z',
             'Realized Profit/Loss': '0.0',
             'State': 'OPEN',
             'Trade ID': '14',
             'Unrealized Profit/Loss': '-205.45'}}