简体   繁体   中英

Use Hyphen in key in Python dict

I have to use hyphen in key using python dict. But it is not working can anyone tell me how to fix this issue

dict1 = dict(with_underscore = "working")
print(dict1)
dict2 = dict(with-hyphen = "Not working")
print(dict2)

Error:

dict2 = dict(with-hyphen = "Not working")
                ^
   SyntaxError: invalid syntax

The problem is not that keys can't have hyphens. Since they are just strings, they can. They problem is that the hyphen corresponds to the subtraction operator. So, python tries to evaluate the expression with-hyphen . That's a problem because the left of an assignment can't be an expression (for other reasons too).

Just use the regular mydict = {'key-with-hyphen': 'value'}

A key with a hyphen is fine; that doesn't mean all key/value pairs can be represented by a keyword argument, since those are restricted to valid identifiers. You have to use one of the other forms, for example,

dict2a = dict([("with-hyphen", "Not working")])
dict2b = {"with-hyphen": "Not working"}
dict2c = dict(**{"with-hyphen": "Not working"})

(The last one is a little silly, but demonstrates that the key/value pairs of an existing dictionary can be passed without explicitly using keyword argument syntax.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM