said
said

Reputation: 476

Assign a Range of Numbers to a Single Key with Dictionaries

I was working on a dictionary, but I came up with an issue. And the issue is, I want to be able to use more than 1 number in order to reference a key in a dictionary.

For example, I want the range of numbers between 1 and 5 to be all assigned to, let's say, "apple". So I came up with this:

my_dict['apple'] = range(1,5)

At the program's current state, its far from being able to run, so testing is an issue, but I do not receive any issues from my editor. I was just wondering, is this the correct way to go about this? Or is there a better way?

Thanks.

EDIT:

A little more info: I want to make a random integer with the randint function. Then, after Python has generated that number, I want to use it to call for the key assigned to the value of the random integer. Thing is, I want to make some things more common than others, so I want to make the range of numbers I can call it with larger so the chance of the key coming up becomes likelier. Sorry if it doesn't make much sense, but at the current state, I really don't even have code to show what I'm trying to accomplish.

Upvotes: 0

Views: 3363

Answers (2)

Brian Lee
Brian Lee

Reputation: 158

You have the dictionary backwards. If you want to be able to recall, e.g., 'apple' with any of the numbers 1-5, you'd need the numbers to be the keys, not the values.

for i in range(1,6):  # range(a,b) gives [a,b)
    my_dict[i] = 'apple'

etc. Then, my_dict[4] == 'apple' and the same is true for the other values in the range.

This can create very large dictionaries with many copies of the same value.

Alternately, you can use range objects as dictionary keys, but the testing will be a bit more cumbersome unless you create your own class.

my_dict[range(1,6)] = 'apple'
n = random.randint(1, 5)

for key in my_dict:
    if n in key:
        print(my_dict[key])

...prints apple.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

The value in a dictionary can be any arbitrary object. Whether it makes sense to use a given type or structure as a value only makes sense in the context of the complete script, so it is impossible to tell you whether it is the correct solution with the given information.

Upvotes: 0

Related Questions