Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 742781
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T08:47:13+00:00 2026-05-14T08:47:13+00:00

I am looking to create a dictionary with ‘roll-back’ capabilities in python. The dictionary

  • 0

I am looking to create a dictionary with ‘roll-back’ capabilities in python. The dictionary would start with a revision number of 0, and the revision would be bumped up only by explicit method call. I do not need to delete keys, only add and update key,value pairs, and then roll back. I will never need to ‘roll forward’, that is, when rolling the dictionary back, all the newer revisions can be discarded, and I can start re-reving up again. thus I want behaviour like:

>>> rr = rev_dictionary()
>>> rr.rev
0
>>> rr["a"] = 17
>>> rr[('b',23)] = 'foo'
>>> rr["a"]
17
>>> rr.rev
0
>>> rr.roll_rev()
>>> rr.rev
1
>>> rr["a"]
17
>>> rr["a"] = 0
>>> rr["a"]
0
>>> rr[('b',23)]
'foo'
>>> rr.roll_to(0)
>>> rr.rev
0
>>> rr["a"]
17
>>> rr.roll_to(1)
Exception ... 

Just to be clear, the state associated with a revision is the state of the dictionary just prior to the roll_rev() method call. thus if I can alter the value associated with a key several times ‘within’ a revision, and only have the last one remembered.

I would like a fairly memory-efficient implementation of this: the memory usage should be proportional to the deltas. Thus simply having a list of copies of the dictionary will not scale for my problem. One should assume the keys are in the tens of thousands, and the revisions are in the hundreds of thousands.

We can assume the values are immutable, but need not be numeric. For the case where the values are e.g. integers, there is a fairly straightforward implementation (have a list of dictionaries of the numerical delta from revision to revision). I am not sure how to turn this into the general form. Maybe bootstrap the integer version and add on an array of values?

all help appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T08:47:14+00:00Added an answer on May 14, 2026 at 8:47 am

    Have just one dictionary, mapping from the key to a list of (revision_number, actual_value) tuples. Current value is the_dict[akey][-1][1]. Rollback merely involves popping the appropriate entries off the end of each list.

    Update: examples of rollback

    key1 -> [(10, ‘v1-10’), (20, ‘v1-20’)]

    Scenario 1: current revision is 30, rollback to 25: nothing happens

    Scenario 2: current 30, back to 15: pop last entry

    Scenario 3: current 30, back to 5: pop both entries

    Update 2: faster rollback (with trade-offs)

    I think your concern about popping every list is better expressed as “needs to examine every list to see if it needs popping”. With a fancier data structure (more memory, more time to maintain the fancy bits in add and update operations) you can reduce the time to roll back.

    Add an array (indexed by revision number) whose values are lists of the dictionary values that were changed in that revision.

    # Original rollback code:
    for rlist in the_dict.itervalues():
        if not rlist: continue
        while rlist[-1][0] > target_revno:
            rlist.pop()
    
    # New rollback code
    for revno in xrange(current_revno, target_revno, -1):
        for rlist in delta_index[revno]:
            assert rlist[-1][0] == revno
            del rlist[-1] # faster than rlist.pop()    
    del delta_index[target_revno+1:]
    

    Update 3: full code for fancier method

    import collections
    
    class RevDict(collections.MutableMapping):
    
        def __init__(self):
            self.current_revno = 0
            self.dict = {}
            self.delta_index = [[]]
    
        def __setitem__(self, key, value):
            if key in self.dict:
                rlist = self.dict[key]
                last_revno = rlist[-1][0]
                rtup = (self.current_revno, value)
                if last_revno == self.current_revno:
                    rlist[-1] = rtup
                    # delta_index already has an entry for this rlist
                else:
                    rlist.append(rtup)
                    self.delta_index[self.current_revno].append(rlist)
            else:
                rlist = [(self.current_revno, value)]
                self.dict[key] = rlist
                self.delta_index[self.current_revno].append(rlist)
    
        def __getitem__(self, key):
            if not key in self.dict:
                raise KeyError(key)
            return self.dict[key][-1][1]
    
        def new_revision(self):
            self.current_revno += 1
            self.delta_index.append([])
    
        def roll_back(self, target_revno):
            assert 0 <= target_revno < self.current_revno
            for revno in xrange(self.current_revno, target_revno, -1):
                for rlist in self.delta_index[revno]:
                    assert rlist[-1][0] == revno
                    del rlist[-1]
            del self.delta_index[target_revno+1:]
            self.current_revno = target_revno
    
        def __delitem__(self, key):
            raise TypeError("RevDict doesn't do del")
    
        def keys(self):
            return self.dict.keys()
    
        def __contains__(self, key):
            return key in self.dict
    
        def iteritems(self):
            for key, rlist in self.dict.iteritems():
                yield key, rlist[-1][1]
    
        def __len__(self):
            return len(self.dict)
    
        def __iter__(self):
            return self.dict.iterkeys()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 357k
  • Answers 357k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The other answers are correct. Here is some code you… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer you ruin the noConflict concept by reassigning the jquery to… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer If you get that particular error, you don't actually have… May 14, 2026 at 9:40 am

Related Questions

No related questions found

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.