0

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"
    }
  }
}

2 Answers 2

1

You can use list comprehension, like this

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

Output

['Title col1', 'Title col2', 'Title col3']
Sign up to request clarification or add additional context in comments.

Comments

0

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()]

2 Comments

SyntaxError: invalid syntax >>>
@user3001937 - I don't understand. My code was tested in Python 3.3 and Python 2.7 and it worked fine. What is wrong? Your dictionary sample has an extra closing curly brace. Perhaps that is the issue? (notice that I simply ignored this in my code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.