Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running python 3.9 code on python 3.7 in google colab

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading