Alex Rivera | Logout

Why are 008 and 009 invalid keys for Python dicts?

Asked 2009-06-14T02:12:20.650
13

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?

Edit
Report

2 Answers

28

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.

answered 2009-06-14T02:16:52.900
10

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.

answered 2009-06-14T02:16:19.470

Your Answer