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 893805
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T14:16:45+00:00 2026-05-15T14:16:45+00:00

I want to write a container class that acts like a dictionary (actually derives

  • 0

I want to write a container class that acts like a dictionary (actually derives from a dict), The keys for this structure will be dates.

When a key (i.e. date) is used to retrieve a value from the class, if the date does not exist then the next available date that preceeds the key is used to return the value.

The following data should help explain the concept further:

Date (key)      Value
2001/01/01      123
2001/01/02       42
2001/01/03      100
2001/01/04      314
2001/01/07      312
2001/01/09      321

If I try to fetch the value associated with key (date) ‘2001/01/05’ I should get the value stored under the key 2001/01/04 since that key occurs before where the key ‘2001/01/05’ would be if it existed in the dictionary.

In order to do this, I need to be able to do a search (ideally binary, rather than naively looping through every key in the dictionary). I have searched for bsearch dictionary key lookups in Python dictionaries – but have not found anything useful.

Anyway, I want to write a class like that encapsulates this behavior.

This is what I have so far (not much):

#
class NearestNeighborDict(dict):
#
"""
#
a dictionary which returns value of nearest neighbor 
if specified key not found
#
"""

def __init__(self, items={}):
    dict.__init__(self, items)


def get_item(self, key):
    # returns the item stored with the key (if key exists)
    # else it returns the item stored with the key
  • 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-15T14:16:46+00:00Added an answer on May 15, 2026 at 2:16 pm

    You really don’t want to subclass dict because you can’t really reuse any of its functionality. Rather, subclass the abstract base class collections.Mapping (or MutableMapping if you want to also be able to modify an instance after creation), implement the indispensable special methods for the purpose, and you’ll get other dict-like methods “for free” from the ABC.

    The methods you need to code are __getitem__ (and __setitem__ and __delitem__ if you want mutability), __len__, __iter__, and __contains__.

    The bisect module of the standard library gives you all you need to implement these efficiently on top of a sorted list. For example…:

    import collections
    import bisect
    
    class MyDict(collections.Mapping):
      def __init__(self, contents):
        "contents must be a sequence of key/value pairs"
        self._list = sorted(contents)
      def __iter__(self):
        return (k for (k, _) in self._list)
      def __contains__(self, k):
        i = bisect.bisect_left(self._list, (k, None))
        return i < len(self._list) and self._list[i][0] == k
      def __len__(self):
        return len(self._list)
      def __getitem__(self, k):
        i = bisect.bisect_left(self._list, (k, None))
        if i >= len(self._list): raise KeyError(k)
        return self._list[i][1]
    

    You’ll probably want to fiddle __getitem__ depending on what you want to return (or whether you want to raise) for various corner cases such as “k greater than all keys in self“.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to write a regex that matches if a string contains XYZ but
I want to write a command that specifies the word under the cursor in
I want to write a function in Python that returns different fixed values based
I want to write a function that takes an array of letters as an
I want to write a word addin that does some computations and updates some
I want to write some JavaScript that will change the onmousedown of a div
I want to write a Swing application in Griffon but I am not sure
I want to write a little DBQuery function in perl so I can have
I want to write a real-time analysis tool for wireless traffic. Does anyone know
I want to write a raw byte/byte stream to a position in a file.

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.