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

Time:01-18

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..

CodePudding user response:

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'

CodePudding user response:

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.

CodePudding user response:

You can use filter combined with next:

def get_item_from_key(input_list, key):
    """Return item corresponding to a specific key"""
    try:
        return next(filter(lambda x: x[0][0] == key, input_list))[1][0]
    except StopIteration:
        return None

So, if the input list is a = [[['name1', 'name2'], [0, 1]], [['name3', 'name4'], [2, 3]]], you can ask for any key you are interested into:

get_item_from_key(a, 'name1')  # this will return 0
get_item_from_key(a, 'name3')  # this will return 2
get_item_from_key(a, 'name2')  # this will return None
get_item_from_key(a, 'name5')  # this will return None

CodePudding user response:

Similar to @Zach Young's answer, you can create a list of dictionaries by zipping pairs and using the dict constructor from the sublists. Then using collections.ChainMap, create a single view.

from collections import ChainMap
dct = ChainMap(*[dict(zip(*sublist)) for sublist in lst])

Then

>>> print(dct['name1'])
n1

>>> print(dct['name3'])
n3
  •  Tags:  
  • Related