• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • 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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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