ZA09
ZA09

Reputation: 91

TypeError: 'type' object is not subscriptable in function python

I'm trying to run the following code which counts the keywords in the specific value of the dictionary but it always shows me TypeError: 'type' object is not subscriptableas marked the error in the code as well. can someone please check and help me to solve this issue. Thanks

from collections import Counter
import json  # Only for pretty printing `data` dictionary.


def get_keyword_counts(text: str, keywords: list[str]) -> dict[str, int]:
    return {
        word: count for word, count in Counter(text.split()).items()
        if word in set(keywords)
    }
// TypeError: 'type' object is not subscriptable

def main() -> None:
    data = {
        "policy": {
            "1": {
                "ID": "ML_0",
                "URL": "www.a.com",
                "Text": "my name is Martin and here is my code"
            },
            "2": {
                "ID": "ML_1",
                "URL": "www.b.com",
                "Text": "my name is Mikal and here is my code"
            }
        }
    }
    keywords = ['is', 'my']
    for policy in data['policy'].values():
        policy |= get_keyword_counts(policy['Text'], keywords)
    print(json.dumps(data, indent=4))


if __name__ == '__main__':
    main()

Upvotes: 0

Views: 3480

Answers (1)

Sandeep Rawat
Sandeep Rawat

Reputation: 214

If you are defining type of your parameters then don't directly use list or dict, instead use List or Dict from typing module.

from typing import List, Dict

def get_keyword_counts(text: str, keywords: List[str]) -> Dict[str, int]:
    ...

Upvotes: 1

Related Questions