Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported operand type(s) for |: 'list' and 'list'

In Python, I want to write a list comprehension to iterate over the union of the keys for 2 dictionaries. Here's a toy example:

A = {"bruno":1, "abe":2}.keys()
B = {"abe":5, "carlton":10}.keys()

>>>[ k for k in A | B ]

I'm getting the error:

Traceback (most recent call last)
<ipython-input-221-ed92ac3be973> in <module>()
      2 B= {"abe":5, "carlton":10}.keys()
      3 
----> 4 [ k for k in A|B]

TypeError: unsupported operand type(s) for |: 'list' and 'list'

The comprehension works just fine for 1 dictionary. For example:

>>>[ k for k in A]
['bruno', 'abe']

Not sure where the error is. I'm following an example in a textbook and according to the book, this type of union and intersection operator should work fine. Please let me know your thoughts. Thank you.

like image 727
wubr2000 Avatar asked Jan 11 '23 20:01

wubr2000


1 Answers

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]
like image 109
Martijn Pieters Avatar answered Jan 16 '23 19:01

Martijn Pieters