Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Selecting only a specific key-value pair inside object

I have this structure:

attributes_json = {
  "attributes": [
    {
      "color": "blue",
      "id": 78923,
      
    {
      "color": "red",
      "id": 321

I wanna select only the "color" key and its values and then put them inside a list, how can I do that in Python?

I have tried this so far but it only gives the first color:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lista = [item for item in attributes_json['attributes'][0]['color']]

>Solution :

I am assuming that the structure is a dictionary with a key "attributes", and "attributes" is a list of dictionaries, each with a key "color". You have the right idea, but you are only accessing the first entry. You need to loop over the list of dictionaries like so:

attributes_list = attributes_json["attributes"]

colors = []
for entry in attributes_list:
    color = entry["color"]
    colors.append(color)

In list comprehension form,

colors = [entry["color"] for entry in attributes_json["attributes"]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading