python - 使用python从JSON dict中提取多个元素
问题描述
在 Python 中,我的 JSON 格式如下:
lists = [
{
"id": 1,
"data": {
"id": "1",
"title": "Title1",
"list_category": "green",
"list_group": ["foo", "bar"],
"tag_Number": ["One","Three","Four","Seven"],
"tag_ABCD": ["B", "C", "D", "E"]
}
},
{
"id": 2,
"data": {
"id": "32",
"title": "Title32",
"list_category": "blue",
"list_group": ["foo2", "bar2"],
"tag_Number": ["One","Three","Four","Seven"],
"tag_ABCD": ["B", "C", "D", "E"]
},
...
我想写不同的函数来从这些列表中提取不同类型的数据。例如,为了提取标题和 ID,我编写了以下函数:
def getTitle():
index_list = []
index_dict = dict()
for x in checklists:
val = ast.literal_eval(x["data"])
Index = dict(id= x['id'], title = val["title"])
index_dict[x['id']]=Index
return index_dict
我的问题是,当我尝试提取其他值时,例如tag_ABCD
,我尝试通过以下方式更改我的函数:
def getTag():
index_list = []
index_dict = dict()
for x in checklists:
val = ast.literal_eval(x["data"])
_val = ast.literal_eval(x["val"])
Index = dict(id= x['id'], tag = _val["tag_ABCD"])
index_dict[x['id']]=Index
return index_dict
但它不会返回正确的元素。
另一个问题(附带问题..):当我想向字典添加第三个元素时,为什么不能返回我的数据?
def getTitle():
index_list = []
index_dict = dict()
for x in checklists:
val = ast.literal_eval(x["data"])
Index = dict(id= x['id'], title = val["title"], list_category = val["list_category"])
index_dict[x['id']]=Index
return index_dict
对于我的每一个变体,我都会遇到相同的错误:
KeyError:'list_category'
解决方案
编写所需函数的一种绝妙方法是使用列表理解和字典理解。请参阅此处了解这些工作原理:https ://www.smallsurething.com/list-dict-and-set-comprehensions-by-example/
代码可能如下所示:
def title_id(the_list):
return {id: title for (id, title) in [(i["id"], i["title"]) for i in the_list]}
至于您在 list_category 周围的错误,我敢打赌您列表中的一个字典没有那个键。要查看发生了什么,请使用 try-except 并在出现键错误的情况下打印 val。
推荐阅读
- verilog - 如何正确处理零位宽情况?
- node.js - 如何创建一个 ID 是另一个模型的外键的模型
- c++ - 如何避免在 C++ 中调用两次析构函数?
- c# - 对象引用未设置为对象的实例/因为我的 TempData 仍然为空
- mongodb - Mongo DB - 独立和 1 节点副本集之间的区别
- c# - 如何从 jsonconvert.deserializeobject 获取令牌值
- docker - 容器运行后如何将Conainter的目录挂载到另一个目录中?
- python - tkinter 加法/减法计算器问题
- ios - CLLocationManagerDelegate didFailError 总是回调错误是 CLError 吗?
- vba - PowerPoint 自动填充形状