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:
lista = [item for item in attributes_json['attributes'][0]['color']]
CodePudding user response:
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"]]
CodePudding user response:
attributes = attributes_json["attributes"]
color=[] for x in attributes: colors = x['color'] color.append('color')