从文本文件中的数据嵌套字典



我是python的新手,我正在尝试创建一个在JSON文件中输出的字典,其中包含来自文本文件的数据。所以文本文件就是这个。

557e155fc5f0 557e155fc5f0 1 557e155fc602 1
557e155fc610 557e155fc610 2
557e155fc620 557e155fc620 1 557e155fc626 1
557e155fc630 557e155fc630 1 557e155fc636 1
557e155fc640 557e155fc640 1
557e155fc670 557e155fc670 1 557e155fc698 1
557e155fc6a0 557e155fc6a0 1 557e155fc6d8 1

前两条线路的期望输出为

{ "functions": [
{
"address": "557e155fc5f0",
"blocks": [
"557e155fc5f0": "calls":{1}
"557e155fc602": "calls":{1}
]
},
{
"address": " 557e155fc610",
"blocks": [
" 557e155fc610": "calls":{2}
]
},

我已经写了一个剧本开始,但我不知道如何继续。

import json
filename = 'calls2.out'       # here the name of the output file
funs = {}
bbls = {}
with open(filename) as fh:     # open file 
for line in fh:            # walk line by line
if line.strip():       # non-empty line?
rtn,bbl = line.split(None,1) # None means 'all whitespace', the default
for j in range(len(bbl)):
funs[rtn] =  bbl.split()
print(json.dumps(funs, indent=2, sort_keys=True))
#json = json.dumps(fun, indent=2, sort_keys=True)  # to save it into a file
#f = open("fout.json","w")
#f.write(json)
#f.close()

这个脚本给我这个输出

"557e155fc5f0": [
"557e155fc5f0",
"1",
"557e155fc602",
"1"
],
"557e155fc610": [
"557e155fc610",
"2"
],
"557e155fc620": [
"557e155fc620",
"1",
"557e155fc626",
"1"
],
funs[rtn] =  bbl.split()

在这里,您将"557e155fc5f0", "1"作为值添加到rtn键,因为此时bbl是557e155fc5f0 1,但您希望将其添加为字典。

temp_dict = {bbl.split()[0]: bbl.split()[1]}
funs[rtn] = temp_dict

这将为您提供以下json:

{
"557e155fc6a0": {
"557e155fc6a0": "1"
}
}

如果你需要调用作为json中的密钥,你需要扩展一点:

temp_dict = {bbl.split()[0]: {"calls": bbl.split()[1]}}
funs[rtn] = temp_dict

给你这个:

{
"557e155fc6a0": {
"557e155fc6a0": {
"calls": "1"
}
}
}

另外,您的示例json格式不正确,我想您想要这样的东西:

{
"functions": {
"address": "557e155fc5f0",
"blocks": {
"557e155fc5f0": {
"calls": 1
},
"557e155fc602": {
"calls": 1
}
}
},
"address": " 557e155fc610",
"blocks": {
"557e155fc610": {
"calls": 2
}
}
}

我会尝试一个在线JSON编辑器来测试/创建示例。

希望它能有所帮助!

最新更新