Question : Can i create a dictionary in python that uses ranges?

I understand how a standard dictionary works in Python. If for example you have a dictionary like the one on line one of the code section. Is it possible to modify that to use a range of values so you would end up with something like this:

1-3   -- abc
4-8   -- def
9-12 -- ghi

I would appreaciate any help or advice on this.

Many thanks
Code Snippet:
1:
dict([(1, 'abc'), (4, 'def'), (9, 'ghi')])
Open in New Window Select All

Answer : Can i create a dictionary in python that uses ranges?

No, that is not how dictionaries work. You must provide the key: dictname['1-3'] would return 'abc'.

However, in python you can implement your own dictionary object. Try this:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
class mydict(dict):
    def __getitem__(self,key):
        if key in self.keys():
            return self[key]
        ranges = []
        for k in self.keys():
            start,stop = k.split('-')
            ranges.append((int(start),int(stop)))
        ranges.sort()
        key = int(key)
        for start,stop in ranges:
            if key>=start and key<=stop:
                return dict.__getitem__(self,"%s-%s"%(start,stop))
 
if __name__=='__main__':
    d = mydict({'1-3':'abc','4-8':'def','9-12':'ghi'})
    print '2:',d[2]
    d['13-18'] = 'jkl'
    print '15:',d[15]
    print "'16':",d['16']
    print d.keys()
    print d.values()
    print d
Open in New Window Select All
Random Solutions  
 
programming4us programming4us