Reputation: 45
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.
Upvotes: 0
Views: 173
Reputation: 110301
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")
Upvotes: 2
Reputation: 14103
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
Upvotes: 3