0

Let's say I have a dictionary like this:

my_dict = {
           hey: onevalue,
           hat: twovalue,
           how: threevalue
           }

Is there any way to account for a reference to a key while having a variable, say a number in it?

such as my_dict['hey1'] = onevalue or my_dict['hey2'] = onevalue

I'm trying to allow for such a variable instead of stripping the numbers from the reference to the key. Thank you in advance.

numb3rs1x
  • 4,673
  • 5
  • 31
  • 44
  • So you want to get `onevalue` when you have the key `hey1` or `hey2`? – sberry Jul 25 '13 at 05:38
  • I'm not quite sure I understand what you're trying to do here. Ignore the digits at the end for both getting and setting? – Joachim Isaksson Jul 25 '13 at 05:39
  • That would be a yes to both. I want to be able to add a digit to the key and have it return the same value regardless of what's after the key. – numb3rs1x Jul 25 '13 at 05:45

2 Answers2

0

There is not. Due to how dicts work (as a hash table), they have no way to accommodate what you want. You will have to create your own type and define the __*item__() methods to implement your logic.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Based on where I'm at with python, it would be less frustrating and more educational just to strip the trailing characters before referencing the key. Thanks for the quick responses! – numb3rs1x Jul 25 '13 at 14:20
0

Building on this answer, you can define your own dict compatible type to strip trailing digits;

import collections

class TransformedDict(collections.MutableMapping):
    """A dictionary which applies an arbitrary key-altering function before accessing the keys"""

    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs)) # use the free update to set keys

    def __getitem__(self, key):
        return self.store[self.__keytransform__(key)]

    def __setitem__(self, key, value):
        self.store[self.__keytransform__(key)] = value

    def __delitem__(self, key):
        del self.store[self.__keytransform__(key)]

    def __iter__(self):
        return iter(self.store)

    def __len__(self):
        return len(self.store)

    def __keytransform__(self, key):
        for i in xrange(len(key)-1,-1,-1):
          if not key[i].isdigit():
            break
        return key[:i]

a = TransformedDict()
a['hello'] = 5
print a['hello123']

>>> 5
Community
  • 1
  • 1
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294