在Python中提取包含Json字段的数组

时间:2013-11-27 00:52:22

标签: python json

我想提取一个包含特定字段的数组。 循环在“d”的对象中并存储“data2”的所有字段。 在这种情况下,我们将有Array_ = [“Title col1”,“Title col2”,“Title col3”]

d = {
    "row1": {
      "data1": "0.87", 
      "data2": "Title col1", 
      "data3": "14.4878", 
      "data4": "Title row1"
    }, 
    "row2": {
      "data1": "15352.3", 
      "data2": "Title col2", 
      "data3": "14.9561", 
      "data4": "Title row2"
    }, 
    "row3": {
      "data1": "0", 
      "data2": "Title col3", 
      "data3": "16.8293", 
      "data4": "Title row3"
    }
  }
}

2 个答案:

答案 0 :(得分:1)

您可以使用list comprehension,就像这样

print [v["data2"] for v in d.values()]

<强>输出

['Title col1', 'Title col2', 'Title col3']

答案 1 :(得分:0)

您可以使用list comprehension

>>> d = {
...     "row1": {
...       "data1": "0.87",
...       "data2": "Title col1",
...       "data3": "14.4878",
...       "data4": "Title row1"
...     },
...     "row2": {
...       "data1": "15352.3",
...       "data2": "Title col2",
...       "data3": "14.9561",
...       "data4": "Title row2"
...     },
...     "row3": {
...       "data1": "0",
...       "data2": "Title col3",
...       "data3": "16.8293",
...       "data4": "Title row3"
...     }
...   }
>>> Array_ = [x["data2"] for x in d.values()]
>>> Array_
['Title col1', 'Title col2', 'Title col3']
>>>

请注意,上述代码假定d.values返回的所有项都有"data2"项。但是,如果情况并非如此,那么您可以使用dict.get来避免KeyError

Array_ = [x.get("data2") for x in d.values()]