• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 358
  • Last Modified:

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
dict([(1, 'abc'), (4, 'def'), (9, 'ghi')])

Open in new window

0
kenkenyon
Asked:
kenkenyon
  • 5
  • 5
1 Solution
 
Roger BaklundCommented:
Your keys are 1, 4 and 9. "1-3" and "4-8" is constructed by looking at the next key: 3 = 4-1, and 8=9-1. But where does 12 come from?
0
 
kenkenyonAuthor Commented:
This is just an example, so i just choose 12 at random. Is it important to look at the next key?

Thanks
0
 
Roger BaklundCommented:
>> Is it important to look at the next key?

Depends. What do you mean by ranges? I am just guessing what you want based on your example.

Is this what you want:

dict([('1-3', 'abc'), ('4-8', 'def'), ('9-12', 'ghi')])
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
kenkenyonAuthor Commented:
Yes, is that how you implement it in Python?
0
 
Roger BaklundCommented:
Or maybe this:
d = dict([(1, 'abc'), (4, 'def'), (9, 'ghi')])
for i in range(len(d.keys())):
    print "%d-%-2d -- %s"%(L[i],L[i+1]-1 if i<len(d.keys())-1 else 12,d[L[i]])

Open in new window

0
 
Roger BaklundCommented:
>> is that how you implement it in Python?

Implement what? This is a hardcoded dictionary:

dict([('1-3', 'abc'), ('4-8', 'def'), ('9-12', 'ghi')])

The dict() function returns a dictionary. It is the same as this:

{'1-3': 'abc', '4-8': 'def',  '9-12': 'ghi'}

The code in my last code snippet is an algorithm, it can be used with different dictionaries as input.

If you describe your requirement in more detail, it would be easier to help you. :)
0
 
kenkenyonAuthor Commented:
Sorry, i've just realised i've not been very clear. Say i have this dictionary:


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

if i then entered:

dictname [2];

for example it would reurn abc, and if i entered dictname[7] it would return def
0
 
Roger BaklundCommented:
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:
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

0
 
kenkenyonAuthor Commented:
ok, i'll do some experiments and report back.

thanks
0
 
kenkenyonAuthor Commented:
Thank you, this is what i wanted.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now