473,785 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Ordered dicts

I have found that in certain situations ordered dicts are useful. I use
an Odict class written in Python by ROwen that I have improved and
updated some for personal use.

So I'm thinking about a possible C version of Odict (maybe fit for the
collections module).

On a 32 bit Win Python 2.5 requires about:
28.2 bytes/element for set(int)
36.2 bytes/element for dict(int:None)

Deleted keys from a dict/set aren't removed, they are tagged as
deleted.
My experience of CPython sources is tiny, I have just read few parts,
so a person much more expert than me can comment the following lines.

During the printing of the set/dict I think such flags are just read
and skipped one after the other.

So I think to keep the insertion order of the keys a simple chained
list is enough, each inserted key has a pointer to the successive one
(even deleted keys). So theoretically an Odict of (int:None) can
require just 40.2 bytes/element :-) (Python Odicts require much more
memory, because they ).
(I don't know if some extra memory for the garbage collector is
necessary, I don't think so.)

The simple linked list has to be managed (tail insertions only), and
scanned from the listHead inside iterating methods like iteritems,
items, values, etc.

If such solution is possibile, then how much difficult is such
implementation?

Bye,
bearophile

Sep 26 '06 #1
6 1836
On 2006-09-26, be************@ lycos.com <be************ @lycos.comwrote :
I have found that in certain situations ordered dicts are
useful. I use an Odict class written in Python by ROwen that I
have improved and updated some for personal use.

So I'm thinking about a possible C version of Odict (maybe fit
for the collections module).
Check out http://sourceforge.net/projects/pyavl/ for a probably
useful sorted mapping type, already implemented in C as an
extension module.

However, I haven't tried it myself.

--
Neil Cerutti
We're going to be exciting. Of course, it was exciting when the
Titanic went down. --Bob Weiss
Sep 26 '06 #2
be************@ lycos.com wrote:
Deleted keys from a dict/set aren't removed, they are tagged as
deleted.
My experience of CPython sources is tiny, I have just read few parts,
so a person much more expert than me can comment the following lines.

During the printing of the set/dict I think such flags are just read
and skipped one after the other.

So I think to keep the insertion order of the keys a simple chained
list is enough, each inserted key has a pointer to the successive one
(even deleted keys).
Not quite. Dictionary slots containing deleted keys are available for re-
use. In an ordinary dictionary you just overwrite the deleted flag with the
new value, but for your ordered dictionary if you did that you would have
to fix up the linked list.

Probably the simplest solution for an odict would be to keep the key in the
dictionary after deletion but mark it as deleted (by setting the value to
null). Then if you reinsert the deleted value it goes back in at its
original order.

The catch of course is that keys then never get released, but you can
always compact an odict by copying it:

d = odict(d)

which should preserve the order but release the deleted keys (assuming no
other references to the original copy).
The simple linked list has to be managed (tail insertions only), and
scanned from the listHead inside iterating methods like iteritems,
items, values, etc.
You would also need to make sure that internal iterations also go through
the linked list order. e.g. resizing a dict currently just goes through
each entry inserting it into the new dict.
If such solution is possibile, then how much difficult is such
implementation?
It sounds easy enough, just a copy of the existing dict code with a few
minor tweaks.

Sep 26 '06 #3
Thank to Neil Cerutti and Duncan Booth for the answers. I have not
tried that C AVL implementation yet.

Duncan Booth:
but for your ordered dictionary if you did that you would have
to fix up the linked list.
To fix the list in constant time you probably need a doubly-linked
list, this requires more memory (or the bad xor trick) and more code
complexity.

Then if you reinsert the deleted value it goes back in at its original order.
Uhm, this doesn't sound good. Thank you, I missed this detail :-)
Then the doubly-linked list, and the links fixing seem necessary...

Bear hugs,
bearophile

Sep 26 '06 #4
be************@ lycos.com wrote:
>Then if you reinsert the deleted value it goes back in at its
original order.

Uhm, this doesn't sound good. Thank you, I missed this detail :-)
Then the doubly-linked list, and the links fixing seem necessary...
An alternative to a doubly linked list might be to never reuse deleted
entries but if the number of deleted entries exceeds a certain proportion
just pack the dictionary.
Sep 26 '06 #5
be************@ lycos.com wrote:
I have found that in certain situations ordered dicts are useful. I use
an Odict class written in Python by ROwen that I have improved and
updated some for personal use.

So I'm thinking about a possible C version of Odict (maybe fit for the
collections module).

On a 32 bit Win Python 2.5 requires about:
28.2 bytes/element for set(int)
36.2 bytes/element for dict(int:None)

Deleted keys from a dict/set aren't removed, they are tagged as
deleted.
My experience of CPython sources is tiny, I have just read few parts,
so a person much more expert than me can comment the following lines.

During the printing of the set/dict I think such flags are just read
and skipped one after the other.

So I think to keep the insertion order of the keys a simple chained
list is enough, each inserted key has a pointer to the successive one
(even deleted keys). So theoretically an Odict of (int:None) can
require just 40.2 bytes/element :-) (Python Odicts require much more
memory, because they ).
(I don't know if some extra memory for the garbage collector is
necessary, I don't think so.)

The simple linked list has to be managed (tail insertions only), and
scanned from the listHead inside iterating methods like iteritems,
items, values, etc.

If such solution is possibile, then how much difficult is such
implementation?
FYI there was a *long* discussion around the need for Speed sprint about
implementing ordered dicts. As the discussion started by your thread has
started to reveal, everyone has just-ever-so-slightly-different
requirements. IIRC the goal was dropped because it wasn't possible to
agree on a specification.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 26 '06 #6
Steve Holden:

I forgot a detail: in the Python version of Odict I use element
deletion is O(n). You need a second dict to improve that (or a duble
linked list of hashing operations, see below).
FYI there was a *long* discussion around the need for Speed sprint about
implementing ordered dicts. As the discussion started by your thread has
started to reveal, everyone has just-ever-so-slightly-different
requirements. IIRC the goal was dropped because it wasn't possible to
agree on a specification.
I received a similar answer about graphs too. But this time I think the
semantic of an ordered dict is simple and clear enough, so I belive a
generally acceptable solution may be found still.
An implementation with double linked lists allows amortized O(1) for
all the usual dict metods, deletions too. Maybe firstkey() lastkey()
methods can be added too, that return the first and last key of the
odict.
The following is a simple example, note that this is a "wrong"
implementation, because you can't scan the keys in the ordered way (you
can scan the values in a ordered way). I presume in a C implementation
you can find the key of a given value. If this isn't possibile without
creating a chain of hashing operations, then I too drop off from this
odict idea :-)

class Odict(dict):
def __init__(self):
dict.__init__(s elf)
self.lh = None # list header
self.lt = None # list tail

def __getitem__(sel f, key):
return dict.__getitem_ _(self, key)[1]

def __setitem__(sel f, key, val):
if key in self:
dict.__getitem_ _(self, key)[1] = val
else:
new = [self.lt, val, None]
dict.__setitem_ _(self, key, new)
if self.lt: self.lt[2] = new
self.lt = new
if not self.lh: self.lh = new

def __delitem__(sel f, k):
if k in self:
pred,_,succ= dict.__getitem_ _(self,k)
if pred: pred[2] = succ
else: self.lh = succ
if succ: succ[0] = pred
else: self.lt = pred
dict.__delitem_ _(self, k)
else: raise KeyError, k

Bye,
bearophile

Sep 27 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
9006
by: Afanasiy | last post by:
I have some code like this... self.write( ''' lots of stuff here with %(these)s named expressions ''' % vars(self) ) Then I wanted to add an item to the dict vars(self), so I tried :
210
10556
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
0
155
by: bruno.desthuilliers | last post by:
On 16 juin, 10:37, Armin Ronacher <armin.ronac...@active-4.comwrote: (snip) +1 "insertion-ordered" dicts are something I often need, and while there are usable workarounds, they either require boilerplate code, introduce external dependancies to (possibly unoptimised) code or make you reinvent the (square) wheel, all of which is (IMHO) below average Python's standard regarding data structures.
4
1560
by: John Townsend | last post by:
Joe had a good point! Let me describe what problem I'm trying to solve and the list can recommend some suggestions. I have two text files. Each file contains data like this: Test file 1234 4567 8975 I want to compare the numbers in each text file. The data set (i.e. the numbers) has a unique identifier: the "test" + the "file". The text files are similar, but may not be exactly the same. My initial idea was to read the text files and...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.