What is the difference between p = {} and p: dict= {} in python?

Viewed 99

I would like to understand what does the expression p: dict = {} mean. To me it is not as intuitive as p = {}. Why does the part : dict add to the expression? To me it appears to not add anything at all.

The code I am looking at is as follows

>>> p = {}
>>> p['s'] = 2
>>> p
{'s': 2}
>>> p: dict = {}
>>> p['a'] = 4
>>> p
{'a': 4}
1 Answers

It's for Python Type Checking. Since Python is a dynamic type language this syntax helps the developer to avoid errors related to type violation. There are tools like mypy which checks these syntax statistically. In your sample code, type for p is defined dict and initialized empty.

Check here as a reference

Related