Python - nested lists - efective checking

Viewed 59

I have a nested list and char variable:

colors =    [
        ("r", [255,0,0]),
        ("g", [0,255,0]),
        ("b", [0,0,255]),
        ("y", [255,0,0]),
        ("p", [255,0,255])
            ]   

char_to_check="b"

How can I (in the most efficient way) check:
1. if char_to_check exists in nested list colors index (r, g, b, etc..)
and
2. if exists (char_to_check) provide values for this char from colors (for example 255,0,0)
else return error (any kind)

2 Answers

Just create a hash (or a dictionary in terms of Python)

colors_dict = dict(colors)

if char_to_check in colors_dict:
    rgb_values = colors_dict[char_to_check]
    # do something

While I like @hspandher answer, depending on the use, that solution may not be the most efficient. @hspandher solution may be efficient if you construct the dictionary once and query it multiple times. However, if you need to find the color value only once (in a large list) then a direct loop would be several times more efficient than constructing a dict:

for c, v in colors[::-1]:
    if c == 'b':
        print(v) # <- do something or return the value
        break
Related