需要将嵌套字典写入文本文件

1 投票
2 回答
1006 浏览
提问于 2025-04-15 13:20

我有一个嵌套的字典,长得像这样:

d={ time1 : column1 : {data1,data2,data3}
            column2 : {data1,data2,data3}        
            column3 : {data1,data2,data3}     #So on.
    time2 : {column1: }       #Same as Above
  }

其中data1、data2、data3代表数据的类型,而不是具体的数据。

我需要把这个字典放到一个文件里,格式是这样的:

时间戳 col1/data1 col1/data2 col1/data3 col2/data1 col2/data2 col2/data3 (依此类推...)

我遇到的问题是,如何确保文本能放在对应的列下面?
比如说,我在时间戳为time1的列14下面放了一些文本,后来又在另一个时间戳中遇到了列14。我该如何跟踪这些列在文本文件中的位置呢?

这些列其实就是一些数字(以字符串的形式表示)。

2 个回答

3

我会使用JSON格式。

在Python 2.6版本中,JSON是直接可以使用的,而在更早的Python版本中,你需要下载并安装它。

try:
    import json
exception ImportError:
    import simplejson as json

out= open( "myFile.json", "w" )
json.dump( { 'timestamp': time.time(), 'data': d }, indent=2 )
out.close()

使用起来很不错。手动编辑也很简单,解析起来也很方便。

1

我会这样做:

#get the row with maximum number of columns
maxrowlen = 0
maxrowkey = ""
for timesid in d.keys():
    if len(timesid.keys()) > maxrowlen:
         maxrowlen = len(timesid.keys())
         maxrowkey = timesid
maxrowcols = sorted(d[maxrowkey].keys())

# prepare the writing
cell_format = "%10r"    # or whatever suits your data

# create the output string
lines = []
for timesid in d.keys(): # go through all times
    line = ""
    for col in maxrowcols:  # go through the standard columns
         colstr = ""
         if col in d[timesid].keys():   # create an entry for each standard column
             colstr += cell_format % d[timesid][col]  # either from actual data
         else:
             colstr += cell_format % ""                      # or blanks
         line += colstr
    lines.append(line)

text = "\n".join(lines)

撰写回答