0

values = ['random word1', 20, 'random word2', 54]

values = list(map(list,zip(values[::2], values[1::2])))

print(values)

[['random word1', 20], ['random word2', 54]]

Now I want to fetch values like this:

if ‘random word2’ in values:

get the value associated with random word 2 which is in this case 54.

Note: string words and values are random.

How can I do that?

I need to fetch the correct value.

1
  • Why not save the data in a dict instead of a list of tuples? Commented Oct 25, 2022 at 14:10

2 Answers 2

3

I think a dictionary over a list is the way to go

d = dict(zip(values[::2], values[1::2]))
print(d['random word1'])  # -> 20
Sign up to request clarification or add additional context in comments.

Comments

2
try:
    value = values[values.index("random words2") + 1]
except ValueError:
    value = None 

Or, if you need to fecth more values, convert your list to a dictionary and then use the get method. Even for 2 retrievals this will already be more efficient, algorithmically wise:

# make N 2-tuples treating the odd-positioned elements as keys and 
# even ones as values, and call the dict constructor with that:
v = dict([i:i+2] for i in range(0, len(values), 2))
v.get("random word2") 

2 Comments

I tried your first method, when the list is like this: ['random word1', 20, 'random word2', 54] it works but when the list is like this: [['random word1', 20], ['random word2', 54]] it doesn’t work. It says "random word2" is not in list. What is the fix?
Also I am using this to fetch only 1 value thats why I would like to use the first method you have provided.

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.