使用python从JSON字典中提取多个元素

时间:2018-09-06 17:30:39

标签: python json python-2.7

在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

对于我的每一个variatoins,我都会遇到相同的错误:

  

KeyError:'list_category'

1 个答案:

答案 0 :(得分:1)

编写列表所需的功能的一种巧妙方法是使用列表理解和dict理解。有关这些工作原理的信息,请参见此处: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和print val。