0

I'm trying to run the following python code on google colab with python 3.7 version but it show's error (the error's syntax is below the code). I think the python code I'm running is written in python 3.9 which will not work in 3.7. I tried to run python 3.9 on google colab but it doesn't work. Can someone please help me to make necessary changes in the code so it can work on python 3.7? 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)
    }



    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))


Error message:

      3 
      4 
----> 5 def get_keyword_counts(text: str, keywords: list[str]) -> dict[str, int]:
      6     return {
      7         word: count for word, count in Counter(text.split()).items()

TypeError: 'type' object is not subscriptable
ZA09
  • 71
  • 6
  • Instead of `dict[str, int]`, try `from typing import Dict` and `Dict[str, int]` – Grismar Jul 06 '22 at 22:09
  • Type annotations are optional. You can just delete them. – Charles Duffy Jul 06 '22 at 22:09
  • Although deleting the code causing the problem makes the problem go away, that does ignore the fact that the code is probably there for a reason, @CharlesDuffy - annotations are optional, but not useless. – Grismar Jul 06 '22 at 22:09
  • Generic built-in types may not be the only feature requiring Python 3.9; best to use the correct Python version instead. – chepner Jul 06 '22 at 22:12
  • Requests to back port arbitrary Python code are not on-topic for Stack Overflow. – chepner Jul 06 '22 at 22:14
  • @Grismar I tried and It gave me the same error – ZA09 Jul 06 '22 at 22:18
  • @chepner can you provide a resource to that effect? I do agree that these questions generally come down to "I didn't read the change notes for the versions that followed", which is why I commented and didn't answer (since I think the question will end up getting deleted or closed), but in itself, asking for help getting newer code to work on an older platform isn't invalid or disallowed. In many cases it may be a valid requirement (like getting code to work in Python scripts on Linux distros that don't have the new Python version) – Grismar Jul 06 '22 at 22:19
  • @ZA09 I just tried myself and on 3.7, the function definition `def f() -> Dict[str, int]:` does not cause an error (after importing `Dict` from `typing`). If you get that error still, you're either using an older version still, or you didn't properly save your code. (note that the `dict` in the definition needs to be spelled with a capital `D`!) – Grismar Jul 06 '22 at 22:21
  • @Grismar I found out the issue. actually I was only importing `Dict` from `typing` which still shows error. Then I import `List` as well from `typing` and now it works. Thank you for your help – ZA09 Jul 06 '22 at 22:36
  • No problem, you're welcome. You should either remove the question, or accept the answer, so that the question no longer appears unanswered. – Grismar Jul 06 '22 at 22:41

1 Answers1

0

You should really use an up to date version of Python if you can. And if you must use an older version for external reasons, ensure that you read the change notes for the intermediate versions.

This particular case is documented here: https://peps.python.org/pep-0585/#implementation

Previous versions of Python require this:

from typing import List, Dict

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

Note the capital D there. (I also updated the reference to list)

Grismar
  • 27,561
  • 4
  • 31
  • 54