Is Python dict an Object?

dictionary, python

Solution

`dict` instances are objects too. But their keys are just not exposed as as attributes.

Exposing the keys as attributes (too or instead of item access) would lead to namespace pollution; you'd never be able to use a `has_key` key, for example. `has_key` is already an attribute on dictionaries:

>>> hasattr({}, 'has_key')
True
>>> {}.has_key
<built-in method has_key of dict object at 0x7fa2a8461940>

Attributes of objects and the contents of dictionaries are two separate things, and the separation is deliberate.

You can always subclass `dict` to add attribute access using the `__getattr__()` hook method:

class AttributeDict(dict):
    def __getattr__(self, name):
        if name in self:
            return self[name]
        raise AttributeError(name)

Demo:

>>> demo = AttributeDict({'foo': 'bar'})
>>> demo.keys()
['foo']
>>> demo.foo
'bar'

Existing attributes on the `dict` class take priority:

>>> demo['has_key'] = 'monty'
>>> demo.has_key
<built-in method has_key of AttributeDict object at 0x7fa2a8464130>

Problem

I have a `dict` like this: ``` >>> my_dict = {u'2008': 6.57, u'2009': 4.89, u'2011': 7.74, ... u'2010': 7.44, u'2012': 7.44} ``` Output with `has_key`: ``` >>> my_dict.has_key(unicode(2012)) True ``` Output with `hasattr`: ``` >>> hasattr(my_dict, unicode(2012)) False ``` I couldn't understand why this behaves differently. I googled and found out that it is because `dict` and objects are different. But, still I couldn't understand the difference properly. (BTW : I am using python 2.7)

Original source