kenkenyon
asked on
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
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')])
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?
ASKER
This is just an example, so i just choose 12 at random. Is it important to look at the next key?
Thanks
Thanks
>> 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')])
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')])
ASKER
Yes, is that how you implement it in Python?
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]])
>> 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. :)
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. :)
ASKER
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok, i'll do some experiments and report back.
thanks
thanks
ASKER
Thank you, this is what i wanted.