3

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)

1
  • Use a dict with your chars as keys :) Commented Nov 9, 2017 at 13:32

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

spot-on answer. Not really a duplicate since OP doesn't know that his data structure can be converted to dict simply.
@Jean-FrançoisFabre Yeah. Luckily for me he already had the data in the right format for instantiation.
Thanks. Works flawlessly.
1

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

1 Comment

UV for explaining that building a dict is only efficient when used more than 1 time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.