Why are 008 and 009 invalid keys for Python dicts?

亡梦爱人 提交于 2019-12-04 02:52:50

问题


Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example:

some_dict = {
    001: "spam",
    002: "eggs",
    003: "foo",
    004: "bar",
    008: "anything", # Throws a SyntaxError
    009: "nothing"   # Throws a SyntaxError
    }

Update: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero?


回答1:


In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:

some_dict = { 
    1: "spam",
    2: "eggs",
    3: "foo",
    4: "bar",
    8: "anything",
    9: "nothing" }

Or if the leading zeros are really important, use strings for the keys.




回答2:


Python takes 008 and 009 as octal numbers, therefore...invalid.

You can only go up to 007, then the next number would be 010 (8) then 011 (9). Try it in a Python interpreter, and you'll see what I mean.




回答3:


In Python (and many other languages), starting a number with a leading "0" indicates an octal number (base 8). Using this leading-zero notation is called an octal literal. Octal numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, etc. So 08 (in octal) is invalid.

If you remove the leading zeros, your code will be fine:

some_dict = 
{ 
    1: "spam",
    2: "eggs",
    3: "foo",
    4: "bar",
    8: "anything",
    9: "nothing" 
}



回答4:


@DoxaLogos is right. It's not that they're invalid keys - they're invalid literals. If you tried to use them in any other context, you'd get the same error.




回答5:


That is because, when you start a number with a 0, it is interpreted as an octal number. Since 008 and 009 are not octal numbers, it fails.

A 0 precedes an octal number so that you do not have to write (127)₈. From the Wikipedia page: "Sometimes octal numbers are represented by preceding a value with a 0 (e.g. in Python 2.x or JavaScript 1.x - although it is now deprecated in both)."



来源:https://stackoverflow.com/questions/991978/why-are-008-and-009-invalid-keys-for-python-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!