首页 > 解决方案 > 使用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'

标签: pythonjsonpython-2.7

解决方案


编写所需函数的一种绝妙方法是使用列表理解和字典理解。请参阅此处了解这些工作原理: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。


推荐阅读