簡體   English   中英

在 Python dict 中的鍵中使用連字符

[英]Use Hyphen in key in Python dict

我必須使用 python dict 在鍵中使用連字符。 但它不起作用誰能告訴我如何解決這個問題

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

錯誤:

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

問題在於鍵不能有連字符。 因為它們只是字符串,所以它們可以。 他們的問題是連字符對應於減法運算符。 所以,蟒蛇嘗試計算表達式with-hyphen 這是一個問題,因為賦值的左邊不能是表達式(也有其他原因)。

只需使用常規的mydict = {'key-with-hyphen': 'value'}

帶連字符的鍵沒問題; 這並不意味着所有鍵/值對都可以由關鍵字參數表示,因為它們僅限於有效標識符。 您必須使用其他形式之一,例如,

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

(最后一個有點傻,但表明可以在不顯式使用關鍵字參數語法的情況下傳遞現有字典的鍵/值對。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM