-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
  • 36,818
  • 81
  • 313
  • 561

2 Answers2

3

Use a generator with next().

next(m['result'] for m in L if m['name'] == 'sara')
Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
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
  • 131,796
  • 23
  • 122
  • 195