Mastodon
Mastodon

Reputation: 151

Finding values in a dictionary if key matches in a range

I have a list and a dictionary:

l = [1, 4, 22, 33]
dict = {1: 'red', 17: 'green', 33: 'blue'};

My goal is to return a new list composed by the values (colors) associated to each element in l if it is between key to key+16.

I know how to retrieve the value if an element of a list matches a key in the dictionary, but I don't know how to consider each key as a range and assign a color for every element in l.

The expected output would be:

['red', 'red', 'green', 'blue']

I know that by generating a list from the dict I would be able to iterate over the two lists, easily finding the values in a range. The problem is that I would be working with two of more than 80,000 elements per list, so the time is too much and I thought a dictionary would be better.

Upvotes: 0

Views: 405

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122096

You can do this simply with integer division:

>>> l = [1, 4, 22, 33]
>>> dct = {1: 'red', 17: 'green', 33: 'blue'}  # don't name your own dictionary dict
>>> [dct[16*((x-1)//16)+1] for x in l]
['red', 'red', 'green', 'blue']

Basically, this maps every number from e.g. 1 to 16 inclusive to 1, every number from 17 to 32 inclusive to 17, etc.

Upvotes: 2

Related Questions