Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Python dict an Object?

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)

like image 729
John Prawyn Avatar asked Jul 20 '13 10:07

John Prawyn


People also ask

Are dictionaries an object?

The data stored in the form of key-value pairs is called an Object or a Dictionary. Objects and dictionaries are similar; the difference lies in semantics. In JavaScript, dictionaries are called objects, whereas, in languages like Python or C#, they are called dictionaries.

What is the difference between dictionary and object in Python?

A dictionary is an arbitrary mapping. An object is a special mapping from names to variables and methods. A class is a language construct that gathers together objects with similar structure and helps to create objects. Objects and classes can be simulated in a straightforward way using functions and dictionaries.

Can dict keys be objects?

Dictionaries in Python Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.

What is dict in Python?

Python's efficient key/value hash table structure is called a "dict". The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces {}.


2 Answers

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>
like image 53
Martijn Pieters Avatar answered Oct 16 '22 15:10

Martijn Pieters


has_key checks for the existence of a key in the dictionary. (One your code defines while creating a dictionary) hasattr checks if the object has an attribute.

Dictionaries are objects, and they have certain attributes. hasattr checks for those.

>>> hasattr(dict, 'has_key')
True
>>> hasattr(dict, 'items')
True
>>> newDict = {'a': 1, 'b':2}
>>> newDict.has_key('a')
True

You can use dir() which lists out the valid attributes for an object.

>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
like image 45
Sukrit Kalra Avatar answered Oct 16 '22 15:10

Sukrit Kalra