TypeError: unsupported operand type for |: 'list' and 'list'

In Python, I want to write a list comprehension to repeat key combining for 2 dictionaries. Here is an example of a toy:

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

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

I get an error message:

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'

Understanding is great for 1 dictionary. For instance:

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

I don’t know where the error is. I follow the example of a textbook and, according to the book, this type of union and intersection operator should work fine. Please share your thoughts. Thank.

+4
source share
1 answer

Python 2 dict.keys()has a list, not a dictionary . Use instead dict.viewkeys():

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

[k for k in A | B]

Python 3, .keys() , .

:

>>> A = {"bruno":1, "abe":2}.viewkeys()
>>> B = {"abe":5, "carlton":10}.viewkeys()
>>> [k for k in A | B]
['carlton', 'bruno', 'abe']

, , Python 3. Python 3 , , Python 2 3.

|, ^, - & ; :

A_dict = {"bruno":1, "abe":2}
B_dict = {"abe":5, "carlton":10}

[k for k in A_dict.viewkeys() | B_dict]
+8

Source: https://habr.com/ru/post/1535880/


All Articles