Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are 008 and 009 invalid keys for Python dicts?

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?

like image 883
Evan Fosmark Avatar asked Jun 14 '09 02:06

Evan Fosmark


People also ask

How do you check if a key exists in a dictionary Python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

Why lists Cannot be used as dictionary keys?

For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.

Can we have duplicate keys in Python dictionary?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.


1 Answers

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.

like image 60
Jacob Avatar answered Sep 19 '22 05:09

Jacob