0

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()
9
  • 1
    Your code as-is works for me (or at least doesn't give a TypeError), on Python 3.9. Commented Jul 6, 2022 at 13:53
  • 4
    Using built-in types in hints like list[str] only became supported in Python 3.9. I'm guessing you are on an older version of Python. You can use typing.List/typing.Dict/etc. instead. Commented Jul 6, 2022 at 13:58
  • @0x5453 Exactly. Or just drop the type specifications if it is okay. Commented Jul 6, 2022 at 13:59
  • I'm running it on google colab and it gives me the above type error in this line def get_keyword_counts(text: str, keywords: list[str]) -> dict[str, int]: Commented Jul 6, 2022 at 14:01
  • Please post the entire traceback message. It lets us know where the problem is. Commented Jul 6, 2022 at 14:03

1 Answer 1

1

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]:
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

I'm doing the same. from typing import List, Dict but it still shows the same error. I'm using python 3.9

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.