-2

I have encountered some unexpected behavior with dicts in python.
It might be because of annotations, but i'm not sure.
Please see the snippet below:

>>> d = {}  # lets create a dictionary and add something to it.
>>> d['a'] = 'a'
>>> d
{'a': 'a'}
>>> d['a']
'a'
>>> # ok all well and good, we know how dicts work, right ?
...
>>> d['z']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>
>>> # yea no key 'z' was inserted. Lets add a colon (:) in the mix 
...
>>> d['z']: d
>>>
>>> # nothing happend! weird...
...
>>> d['z']: d['z']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'z'

>>> # again 'z' was not added to the dict, but what did the colon ???
...
>>> d['z']: d['z']: None
  File "<stdin>", line 1
    d['z']: d['z']: None
                  ^
SyntaxError: invalid syntax
>>>
>>> # NOW the colon gives an SyntaxError !?!
>>> # Lets try to directly use a colon after the dict
...
>>> {'a': 'a'}: ()
  File "<stdin>", line 1
SyntaxError: illegal target for annotation
>>>
>>> # so annotation huh ?
>>> # is it possible to annotate on the fly ?
...
>>> def func(x): return x
... 
>>> d = {'f': func}  # overwrite previous dict 
>>> d['f']: callable
>>> d['f'].__annotations__
{}
>>> # doesn't look like it was taken over
... # lets check if d['f'] returns the callable function: func
...
>>>
>>> def func(x: str) -> callable: return x
... 
>>> d = {'f': func}
>>> d['f'].__annotations__  # lets check for annotations !!
{'x': <class 'str'>, 'return': <built-in function callable>}
>>>
>>> # I'm confused, what does the colon do?
...
>>>

I'm curious why the dict syntax doesn't always react on the given colon (:).
Also the annotations doesn't seem to be the case (or my conclusion is wrong)

So dear readers, what is the purpose of the colon used in the context described above?

2 Answers2

0

Colon is used to separate key and value but it works only if it is in a bracket.

As the document say

Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output

https://docs.python.org/3/tutorial/datastructures.html

HelloWorld
  • 835
  • 2
  • 8
  • 21
0

After long and hard thinking i came to conclusion that objects in dictionaries can be iterables too.
That means the colon is allowed after the square brackets.

>>> d = {'a': 'abcd'}
>>> for letter in d['a']: None # <- see here, look at the placement of the colon
...
  • 1
    This is just the one-line form of a `for` statement. The initial construct you noticed as a variable annotation, allows an optional annotation (such as a type hint, but any expression is valid) following a name. The colon in `d[z]: d` has nothing to do with the use of a colon in a dict display. – chepner Feb 15 '20 at 19:39