0

I am trying to parse the key "tags" from the below JSON.

data = [{
    "12233":{
    "title": "The Title",
    "id": "12233",
    "tags": ["tag1", "tag2", "tag3"],
    },
    "122223":{
    "title": "The Title",
    "id": "122223",
    "tags": ["tag4", "tag5", "tag6"],
    },
    "122344":{
    "title": "The Title",
    "id": "122344",
    "tags": ["tag7", "tag8", "tag9"],
    }
}]

I have tried this so far,

data = data[0]
tags_list = []

for tags in data:
    tags_list.append(tags["122344"])

print(tags_list)

But it only extracts the first object, I want the result to be like this,

tags_list = ["tag1", "tag2", "tag3", "tag4", "tag5", "tag6","tag7", "tag8", "tag9"]
1
  • try using list compression Commented Sep 2, 2021 at 13:28

3 Answers 3

3

is this will solve your problem?

tags_list = [item for k in data for t in k for item in k[t]['tags']]
Sign up to request clarification or add additional context in comments.

Comments

1

Use itemgetter on all values of dictionary data[0] and sum all items to empty list []

from operator import itemgetter

data = [{
    "12233":{
    "title": "The Title",
    "id": "12233",
    "tags": ["tag1", "tag2", "tag3"],
    },
    "122223":{
    "title": "The Title",
    "id": "122223",
    "tags": ["tag4", "tag5", "tag6"],
    },
    "122344":{
    "title": "The Title",
    "id": "122344",
    "tags": ["tag7", "tag8", "tag9"],
    }
}]

tag_getter = itemgetter('tags')
# map to get list of all tags
# Adding all the list of tags to []
sum(map(tag_getter, data[0].values()), [])
['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6', 'tag7', 'tag8', 'tag9']

If you want to merge all tags from all the entries of list then use

from operator import itemgetter
tag_getter = itemgetter('tags')
def all_tags(d):
    return sum(map(tag_getter, d.values()), [])
sum(map(all_tags, data), [])

1 Comment

Lambdas in Python are designed to be anonymous functions. There is no sense in assign one to a variable, making it a named function. It is considered bad practice. If you need that, define a function instead. See (stackoverflow.com/a/25010243/6789321) and (python.org/dev/peps/pep-0008/#programming-recommendations).
0

In stead of a single loop, you need two loops to iterate over the inner dictionaries. Try this :

tags_list = []
for k in data:
    for t in k:
        tags_list.extend(k[t]['tags'])

Output tags_list :

['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6', 'tag7', 'tag8', 'tag9']

Comments

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.