Can this for loop be reduced to one line?

Viewed 67

Python code:

arr = [['name1', 101], ['name2', 234], ['name3', 456]]
nametolookfor = input("Please enter the name: ")
data = 0
for value in arr:
    if value[0] == nametolookfor:
        otherdata = value[1]

I was wondering if the for loop and its contents could be brought down to one line.

I have tried using list comprehensions but can't seem to get it to work.

4 Answers

You can use a list comprehension to filter for array elements where the name matches, then select only the value, and from that retrieve the first:

>>> arr = [['name1', 101], ['name2', 234], ['name3', 456]]
>>> nametolookfor = 'name2'
>>> [v for (n, v) in arr if n == nametolookfor][0]
234

Since your list is a list of key/value pairs where the key is (by definition) unique, you can also make it into a dictionary and have a direct lookup instead:

>>> lookup = dict(arr)
>>> lookup[nametolookfor]
234

Of course, if your arr is static, you can just declare it as a dictionary from the start to save you from having to do the conversion:

>>> lookup = { 'name1': 101, 'name2': 234, 'name3': 456 }
>>> lookup[nametolookfor]
234

I think this should be close to what you want. Using next avoids some boilerplate later to check if the value exists.

next(value[0] for value in are if value[0] == nametolookfor, None)

Yes this is posible in list comprehensions. Follow this

[value[1] for value in arr if value[0] == nametolookfor]

Please enter the name: name1

Output: [101]

Assume your list arr = [['name1', 101], ['name2', 234], ['name3', 456], ['name1', 202], ['name1', 303]] and set input nametolookfor = name1 then result will be

[101, 202, 303]

Try this out:

otherdata = dict(arr)[nametolookfor]

Since the list is a list of key/value pairs where the key is unique, you can convert it into a dictionary and have a direct lookup.

Related