python - 搜索 json 文件返回数据框列中键的一部分
问题描述
我有一个 json 文件。它看起来像这样:
example = {"evaluation user1":{
"results test1": {
"chapter": "Chapter1",
"Chapter_type": "Chemistry1",
"Exercice 1 code:Chem01": "Wright",
"Exercice 2 code:Chem02": "Wrong",
"Exercice 3 code:Chem03": "Wrong",
"userEmail": "user1@mail.com",
},
"results test2": {
"chapter": "Chapter1",
"Chapter_type": "Chemistry2",
"Exercice 1 code:Chem01": "Wrong",
"Exercice 2 code:Chem02": "Wright",
"Exercice 3 code:Chem03": "Wrong",
"userEmail": "user1@mail.com",
}}
}
我需要提取键/值并将它们添加到数据框中。我做了这样的事情:
for key, value in example.items():
if 'evaluation' in key:
for key1, value1 in value.items():
computedValues = {}
computedValues['Email'] = value['userEmail']
computedValues['Chapter'] = value['chapter']
它适用于示例中的“chapter”:“Chapter1”等键/值。
我的问题是我需要提取“练习”键的内容:
Code Answer
Chem01
Email Test Code Answer
user1@mail.com test1 Chem01 Wright
user1@mail.com test1 Chem02 Wrong
user1@mail.com test1 Chem03 Wrong
user1@mail.com test2 Chem01 Wrong
user1@mail.com test2 Chem02 Wright
user1@mail.com test2 Chem03 Wrong
基本上我需要访问列/行中的键/值(如电子邮件),但我需要访问行上练习的部分键/值,因为我可以有很多练习代码而且我不想有数百列。有人可以帮我吗?
解决方案
修改了您的示例代码以构建列表列表:
computedValues = []
for key, value in example.items():
if 'evaluation' in key:
for key1, value1 in value.items():
test0, test = key1.split(" ")
email = value1.pop('userEmail')
chapter = value1.pop('chapter')
chapter_type = value1.pop('Chapter_type')
for key2, value2 in value1.items():
code0, code = key2.split(':')
computedValues.append([email, test, chapter, code, value2])
输出将是:
[['user1@mail.com', 'test1', 'Chapter1', 'Chem01', 'Wright'],
['user1@mail.com', 'test1', 'Chapter1', 'Chem02', 'Wrong'],
['user1@mail.com', 'test1', 'Chapter1', 'Chem03', 'Wrong'],
['user1@mail.com', 'test2', 'Chapter1', 'Chem01', 'Wrong'],
['user1@mail.com', 'test2', 'Chapter1', 'Chem02', 'Wright'],
['user1@mail.com', 'test2', 'Chapter1', 'Chem03', 'Wrong']]
我不明白您为什么要再次尝试将处理后的数据放入 dict 中。如果您澄清最终结果,我可以更新答案。
推荐阅读
- twilio - 将 SIP 域呼叫转发到弹性 SIP 中继
- javascript - 多个实例时动态生成的 jQuery 函数停止工作
- ios - 应用程序崩溃原因:'-[HOV1.itemShowViewController collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 0x7fcc8f6a1320'
- android - 我如何使用密封类来描述具有关联值的有限案例集以及较小的此类值集?
- javascript - 无法识别 Websocket .close()
- oracle - Oracle Blob 存储?
- c - 无法使用 C 中的按值调用方法执行简单函数
- javascript - Ajax POST 请求在允许来源后不起作用
- javascript - 在点击而不是悬停时显示下拉菜单
- c# - 尝试使用 C# 在 Windows 注册表中设置 DWORD 值时出错