user3001937
user3001937

Reputation: 2113

Extracting an array that contains Json fields in Python

I would like to extract make an array that contains a specific field. Looping in the object of "d" and store all the fields of "data2". In this case we will have 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"
    }
  }
}

Upvotes: 0

Views: 147

Answers (2)

user2555451
user2555451

Reputation:

You can use a 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']
>>>

Note that the above code assumes that all of the items returned by d.values have a "data2" key. However, if this isn't always the case, then you can use dict.get to avoid a KeyError:

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

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239473

You can use list comprehension, like this

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

Output

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

Upvotes: 1

Related Questions