Home > Mobile >  How to count/flatten inner list in python
How to count/flatten inner list in python

Time:10-13

So I am trying to count amount of elements in inner list. I have object, which looks like that

{
    "author": [
        {
            "author_id": "1",
            "author_name": "King",
            "languages": [
                {
                    "language": "EN",
                    "books": [
                        {
                            "book_id": "111"
                        },
                        {
                            "book_id": "222"
                        },
                        {
                            "book_id": "333"
                        },
                        {
                            "book_id": "444"
                        },
                        {
                            "book_id": "555"
                        }
                    ]
                },
                {
                    "language": "CZ",
                    "books": [
                        {
                            "book_id": "123"
                        },
                        {
                            "book_id": "45"
                        },
                        {
                            "book_id": "67"
                        },
                        {
                            "book_id": "89"
                        }
                    ]
                }
            ]
        }
    ]
}

so lets assume there is only one Author, so it is ok author = authorList[0], and I want to count amount of books he has in above object. So this author has 5 books assigned to language EN and 4 books for CZ what gives us 9 books.

I was trying to use reduce function, which will return flatter list of only books and after that I can just use len(books). But list(reduce(lambda x, y: x["books"] y["books"], author["languages"])) returns ["language", "books"] as a result, so clearly not what I want.

Any help?

I know I can use nester for loops but I would like to use different apporach.

CodePudding user response:

If you can use jmespath then you can get it like

import jmespath
print(len(jmespath.search("author[*].languages[*].books[][]", data)))

#also if you want to filter on the basis of author_id

print(len(jmespath.search("author[?author_id=='1'].languages[*].books[][]", data)))

Also your code is working fine

author = data["author"][0]
print(list(reduce(lambda x, y: x["books"]   y["books"], author["languages"])))
#[{'book_id': '111'}, {'book_id': '222'}, {'book_id': '333'}, {'book_id': '444'}, {'book_id': '555'}, {'book_id': '123'}, {'book_id': '45'}, {'book_id': '67'}, {'book_id': '89'}]

CodePudding user response:

Very hacky, but how about str(author_dict).count('book_id')? It assumes the book IDs are unique though.

  • Related