Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:Extend the 'dict' class

I have to solve this exercise:

Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when new elements are added.

How do I extend dict? Do I need to have access to the source code for the dict type?

like image 436
Sgotenks Avatar asked Feb 24 '10 17:02

Sgotenks


People also ask

How do you extend a class in a dictionary Python?

You will need to override all the methods that modify the dict as well as the methods that iterate over the dict. Methods that modify the dict include __delitem__ , __setitem__ , clear etc. Methods that iterate the dict include __iter__ , keys , values , items etc. @z3d0r, In Python3, .

How do you extend a dictionary?

In the dictionary extend() means to concatentates the first dictionary with another dictionary. In Python dictionary, the append() function is used to add elements to the keys in the dictionary. In the dictionary extend() means to concatenate the first dictionary with another dictionary.

How do you inherit a dictionary in Python?

In Python, you can do this by inheriting from an abstract base class, by subclassing the built-in dict class directly, or by inheriting from UserDict . In this tutorial, you'll learn how to: Create dictionary-like classes by inheriting from the built-in dict class.

What is __ dict __ in Python?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.


1 Answers

You can either subclass dict or UserDict, since van already talked about UserDict, lets look at dict.

Type help(dict) into an interpreter and you see a big list of methods. You will need to override all the methods that modify the dict as well as the methods that iterate over the dict.

Methods that modify the dict include __delitem__,__setitem__,clear etc.

Methods that iterate the dict include __iter__,keys,values,items etc.

This should get you started

>>> class odict(dict): ...     def __init__(self, *args, **kw): ...         super(odict,self).__init__(*args, **kw) ...         self.itemlist = super(odict,self).keys() ...     def __setitem__(self, key, value): ...          # TODO: what should happen to the order if ...          #       the key is already in the dict        ...         self.itemlist.append(key) ...         super(odict,self).__setitem__(key, value) ...     def __iter__(self): ...         return iter(self.itemlist) ...     def keys(self): ...         return self.itemlist ...     def values(self): ...         return [self[key] for key in self]   ...     def itervalues(self): ...         return (self[key] for key in self) ...  >>> od = odict(a=1,b=2) >>> print od {'a': 1, 'b': 2} >>> od['d']=4 >>> od['c']=3 >>> print od   # look at the `__str__` and `__repr__` methods  {'a': 1, 'c': 3, 'b': 2, 'd': 4} >>> print od.keys() ['a', 'b', 'd', 'c'] >>> print od.values() [1, 2, 4, 3] 
like image 58
John La Rooy Avatar answered Sep 22 '22 23:09

John La Rooy