How get corresponding element in sub list based on input element from the same list python

I've list like this.

list=[[['name1','name2'],[n1,n2]], [['name3','name4'],[n3,n4]]]

I want to get n1 if input is name1

similarly if input if name3 then output should be n3

Note: name1-Type str
      n1-   Type int

Is there is any way to do this?..Pls suggest me solution/Solution steps that i can follow to solve this issue..


Solution 1:

I see building an intermediate lookup dict from my_list, then looking up as you like:

my_list=[
  [['name1','name2'],['n1','n2']], 
  [['name3','name4'],['n3','n4']]
]

lookup = {}

for double_tuple in my_list:
    lhs, rhs = double_tuple
    zipped = zip(lhs, rhs)  # ['name1','name2'],['n1','n2'] → ['name1', 'n1'],['name2','n2']
    lookup.update(dict(zipped))

print(lookup['name1'])  # → 'n1'

Solution 2:

It can be easily solved with a list comprehension:

  1. unpack the elements in the list
  2. filter for k1 == input
  3. get first result, if exists
input_ = "name1"
list_ = [[['name1','name2'],[n1,n2]], [['name3','name4'],[n3,n4]]]
candidates = [v1 
              for (k1, _), (v1, _) in list_
              if k1 == input_]
if len(candidates) == 0:
    print("No such key: " + input_)
else:
    print("Value is " + candidates[0])

Note: I used trailing underscores in the names to avoid overwriting builtin functions (list and input). Overwriting builtin functions is bad practice.