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

Dung Do Tien Oct 22 2021 79

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I am working with Lamda and the list object dictionary.  I have some lines of code as below:

odd_lamda = lambda x: (x + 1) | 1
even_lamda = lambda x: (x + 2) & ~1

object_mapping = {
    'RTL': (odd_lamda, 'N'),
    'RTR': (even_lamda, 'N'),
    'RAL': (odd_lamda, 'R'),
    'LTR': (even_lamda, 'L'),
}

ignore = object_mapping.keys() + ['BN', 'PDF', 'B']
remove = object_mapping.keys() + ['BN', 'PDF']

But I get an exception throw TypeError: unsupported operand type(s) for +: 'dict_keys' and 'list' when I run code above.

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    ignore = object_mapping.keys() + ['BN', 'PDF', 'B']
TypeError: unsupported operand type(s) for +: 'dict_keys' and 'list'

And I am using python 3.x

Anyone can explain it to me? 

How can I solve it?

Thanks for any suggestions.

Have 2 answer(s) found.
  • P

    Praween Kumar Oct 23 2021

    You got issue in line 11 & 12.  In Python 3.x keys() method will not return a list string for you, so you need to use list() method to help convert dictionary to a list string, see example below:

    ignore = list(object_mapping) + ['BN', 'PDF', 'B']
    remove = list(object_mapping) + ['BN', 'PDF']

    #Output

    ['RTL', 'RTR', 'RAL', 'LTR', 'BN', 'PDF', 'B']
    ['RTL', 'RTR', 'RAL', 'LTR', 'BN', 'PDF']

    I hope it helpful for you.

  • D

    Dũng Đô La Oct 23 2021

    You can use list() function to help convert dictionary to a list string:

    odd_lamda = lambda x: (x + 1) | 1
    even_lamda = lambda x: (x + 2) & ~1
    
    object_mapping = {
        'RTL': (odd_lamda, 'N'),
        'RTR': (even_lamda, 'N'),
        'RAL': (odd_lamda, 'R'),
        'LTR': (even_lamda, 'L'),
    }
    
    ignore = list(object_mapping.keys()) + ['BN', 'PDF', 'B']
    remove = list(object_mapping.keys()) + ['BN', 'PDF']
    
    print(ignore)
    print(remove)

    #output

    ['RTL', 'RTR', 'RAL', 'LTR', 'BN', 'PDF', 'B']
    ['RTL', 'RTR', 'RAL', 'LTR', 'BN', 'PDF']
    
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close