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

Basj
  • 41,386
  • 99
  • 383
  • 673

2 Answers2

3

Use a generator with next().

next(m['result'] for m in L if m['name'] == 'sara')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
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'))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219