如何从具有这种特定数据结构的 .txt 文件创建字典?

How can I create a dictionary out of a .txt file with this specific data structure?

我正在使用的 txt 文件包含如下内容:

[
  {
    "Data": "asdf",
    "Monday": "321.247",
    "Tuesday": "27.801",
    "Thursday": "35.235"
  },
  {
    "Data": "whatever",
    "Monday": "321.247",
    "Tuesday": "207.568",
    "Thursday": "31.027",
    "Wednesday": "56.902"
  }
]

我想创建一个具有相同结构的字典,以便我可以将“数据”字段作为第一级键,将工作日作为第二级键,将数值作为值。 我已经尝试使用 json 库导入它,但我真的不知道下一步该做什么,因为我只能用它创建一个列表。

编辑:

做的时候:

with open(".../file.txt") as file:
  data=json.load(file)

type(data)

我得到:

list

我希望得到的是像这样的字典:

data
{
  "asdf" : {
    "Monday": 321.247,
    "Tuesday": 27.801,
    "Thursday": 35.235
  },
"whatever": {
    "Monday": 321.247,
    "Tuesday": 207.568,
    "Thursday": 31.027,
    "Wednesday": 56.902
  }
}

您可以使用 eval,它会在读取文件后创建字典

with open('test', 'r') as reader:
    d = eval(reader.read())
print(d)

输出:

[{'Data': 'asdf', 'Monday': '321.247', 'Tuesday': '27.801', 'Thursday': '35.235'}, {'Data': 'whatever', 'Monday': '321.247', 'Tuesday': '207.568', 'Thursday': '31.027', 'Wednesday': '56.902'}]
# using above data structure you can create your leveled key as you want 

使用这种嵌套的 dict 理解有点棘手,但稍微想一想就会明白(随时要求更多解释..),efficiency-wise 我认为这是最好的方法:

a = [
  {
    "Data": "asdf",
    "Monday": "321.247",
    "Tuesday": "27.801",
    "Thursday": "35.235"
  },
  {
    "Data": "whatever",
    "Monday": "321.247",
    "Tuesday": "207.568",
    "Thursday": "31.027",
    "Wednesday": "56.902"
  }
]

modified_a = {item["Data"]:{key:val for key,val in item.items() if key!="Data"} for item in a}

print(modified_a)

输出:

{'asdf': {'Monday': '321.247', 'Tuesday': '27.801', 'Thursday': '35.235'}, 'whatever': {'Monday': '321.247', 'Tuesday': '207.568', 'Thursday': '31.027', 'Wednesday': '56.902'}}