【问题标题】:Nested dictionary from data in a text file文本文件中数据的嵌套字典
【发布时间】:2018-07-20 08:58:30
【问题描述】:

我是 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"
     ],

【问题讨论】:

  • "557e155fc5f0": "calls":{1} 语法无效。 :{1} 应该是什么?
  • 我编辑了我的答案,如果你需要“通话”作为关键,在你标记它之后,这样你就不会忽视它,以防万一你需要它(;

标签: python json file dictionary text


【解决方案1】:
funs[rtn] =  bbl.split()

在这里您将"557e155fc5f0", "1" 作为值添加到rtnkey,因为此时 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 编辑器来测试/创建示例。

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2021-06-21
    • 2018-04-02
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多