In Python 2, dict.keys()
is a list, not dictionary view. Use dict.viewkeys()
instead:
A = {"bruno":1, "abe":2}.viewkeys()
B = {"abe":5, "carlton":10}.viewkeys()
[k for k in A | B]
Your example would have worked in Python 3, where the .keys()
method has been changed to return a dictionary view by default.
Demo:
>>> A = {"bruno":1, "abe":2}.viewkeys()
>>> B = {"abe":5, "carlton":10}.viewkeys()
>>> [k for k in A | B]
['carlton', 'bruno', 'abe']
It sounds as if your textbook assumes you are using Python 3. Switch textbooks, or use Python 3 to run the examples, don't try to mix the two until you get a lot more experience with the differences between Python 2 and 3.
For the record, a dictionary view supports set operations with the |
, ^
, -
and &
operators against any iterable on the right-hand side; so the following works too:
A_dict = {"bruno":1, "abe":2}
B_dict = {"abe":5, "carlton":10}
[k for k in A_dict.viewkeys() | B_dict]