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"]
JimmyOppa
  • 67
  • 5

3 Answers3

3

is this will solve your problem?

tags_list = [item for k in data for t in k for item in k[t]['tags']]
sarath ravi
  • 463
  • 1
  • 4
  • 13
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), [])
eroot163pi
  • 1,791
  • 1
  • 11
  • 23
  • 1
    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 (https://stackoverflow.com/a/25010243/6789321) and (https://www.python.org/dev/peps/pep-0008/#programming-recommendations). – accdias Sep 02 '21 at 14:06
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']
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56