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