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

TJ1 picture TJ1 · Nov 9, 2013 · Viewed 14.4k times · Source

I am trying to use a Python package called bidi. In a module in this package (algorithm.py) there are some lines that give me error, although it is part of the package.

Here are the lines:

_LEAST_GREATER_ODD = lambda x: (x + 1) | 1
_LEAST_GREATER_EVEN = lambda x: (x + 2) & ~1

X2_X5_MAPPINGS = {
    'RLE': (_LEAST_GREATER_ODD, 'N'),
    'LRE': (_LEAST_GREATER_EVEN, 'N'),
    'RLO': (_LEAST_GREATER_ODD, 'R'),
    'LRO': (_LEAST_GREATER_EVEN, 'L'),
}

# Added 'B' so X6 won't execute in that case and X8 will run its course
X6_IGNORED = X2_X5_MAPPINGS.keys() + ['BN', 'PDF', 'B']
X9_REMOVED = X2_X5_MAPPINGS.keys() + ['BN', 'PDF']

If I run the code in Python 3 I get this error message:

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    from bidi.algorithm import get_display
  File "C:\Python33\lib\site-packages\python_bidi-0.3.4-py3.3.egg\bidi\algorithm.py", line 41, in <module>
    X6_IGNORED = X2_X5_MAPPINGS.keys() + ['BN', 'PDF', 'B']
TypeError: unsupported operand type(s) for +: 'dict_keys' and 'list'

Why there is this error although this is part of the bidi package? Does it have anything to do with my Python version? I appreciate any help on this.

Answer

user2555451 picture user2555451 · Nov 9, 2013

In Python 3.x, dict.keys returns a dictionary view:

>>> a = {1:1, 2:2}
>>> a.keys()
dict_keys([1, 2])
>>> type(a.keys())
<class 'dict_keys'>
>>>

You can get what you want by putting those views in list:

X6_IGNORED = list(X2_X5_MAPPINGS.keys()) + ['BN', 'PDF', 'B']
X9_REMOVED = list(X2_X5_MAPPINGS.keys()) + ['BN', 'PDF']

Actually, you don't even need .keys anymore since iterating over a dictionary yields its keys:

X6_IGNORED = list(X2_X5_MAPPINGS) + ['BN', 'PDF', 'B']
X9_REMOVED = list(X2_X5_MAPPINGS) + ['BN', 'PDF']