user3547740
user3547740

Reputation:

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 it is not taking from?

Whenever I encounter with from as a key in dictionary, I can't use it.

Upvotes: 1

Views: 5616

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124828

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 identifiers only. 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.

Upvotes: 12

Related Questions