Home > Software design >  Search for value in twodimensional list, get value
Search for value in twodimensional list, get value

Time:12-13

Sure totally easy for you: How to get 'Fred' from the search ?


list = [[123, 'Fred'],[234234, 'Martha'],[89182038,'Adam']]
true_or_not = any(123 in sublist for sublist in list)
if true_or_not == True:
  name= ???

CodePudding user response:

You could convert your nested list to a dict and look up the name by ID

nested = [[123, 'Fred'],[234234, 'Martha'],[89182038,'Adam']]
users = {l[0]: l[1] for l in nested}
print(users[123])

OUTPUT

Fred

This is assuming all ID's are unique

CodePudding user response:

A slight improvement to Chris answer:

nested = [[123, 'Fred'], [234234, 'Martha'], [89182038,'Adam']]
users = {id_: name for id_, name in nested}
print(users[123])

I think this makes it more clear how dict is constructed from list of lists.

CodePudding user response:

You can use next():

lst = [[123, "Fred"], [234234, "Martha"], [89182038, "Adam"]]

print(next(name for i, name in lst if i == 123))

Prints:

Fred

You can also specify default value in case 123 is not found:

print(next((name for i, name in lst if i == 123), None))  # returns None if 123 is not found

CodePudding user response:

If you plan doing it once maybe it is not necessary to transform to dict.

nested = [[123, 'Fred'], [234234, 'Martha'],[89182038,'Adam']]
[name for id_, name in nested if id_ == 123][0]
# Fred
  • Related