-1

Let:

M = [{'name': 'john', 'result': 12}, 
     {'name': 'sara', 'result': 20}, 
     {'name': 'karl', 'result': 11}]

If I want to find Sara's result, I thought about:

 M[[m['name'] for m in M].index('sara')]['result']     # hard to read, but works

and

[m['result'] for m in M if m['name'] == 'sara'][0]     # better

Is there an even more natural way to do this in Python?

0

2 Answers 2

3

Use a generator with next().

next(m['result'] for m in L if m['name'] == 'sara')
3
  • Just to be sure to understand, this is to avoid [...][0], is it a better practice?
    – Basj
    Commented May 5, 2018 at 9:45
  • Yes - the advantage is that it stops iterating as soon as a match is found, and doesn't construct an unnecessary list. Commented May 5, 2018 at 9:47
  • 1
    add a default None second parameter to return None instead of StopIteration exception Commented May 5, 2018 at 9:51
3

If you have several lookups to perform, linear search isn't the best option.

Rebuild a dictionary once with the proper key (name):

M = [{'name': 'john', 'result': 12},
     {'name': 'sara', 'result': 20},
     {'name': 'karl', 'result': 11}]

newdict = {d["name"] : d["result"] for d in M}

It creates:

{'john': 12, 'karl': 11, 'sara': 20}

now when you need the result from a name, just do:

print(newdict.get('sara'))

Not the answer you're looking for? Browse other questions tagged or ask your own question.