Frage

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.

War es hilfreich?

Lösung

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]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top