Skip to content Skip to sidebar Skip to footer

Dictionary Declaration In Python

I have declared a dictionary data=dict(key='sadasfd',secret='1213',to='23232112',text='sucess',from='nattu') It is showing error in python, saying that keyword is used. Why does i

Solution 1:

from is a reserved keyword and cannot be used as a keyword argument to the dict() constructor.

Use a {...} dictionary literal instead:

data = {'key': "sadasfd", 'secret': "1213", 
        'to': "23232112", 'text': "sucess", 'from': 'nattu'}

or assign to the key afterwards:

data['from'] = 'nattu'

or avoid using reserved keywords altogether.

Python supports passing arbitrary keywords to a callable, and uses dictionaries to capture such arguments, so it is a logical extension that the dict() constructor accepts keyword arguments. But such arguments are limited to valid Python identifiersonly. If you want to use anything else (reserved keywords, strings starting with integers or containing spaces, integers, floats, tuples, etc.), stick to the Python dict literal syntax instead.

Post a Comment for "Dictionary Declaration In Python"