1

I have a list that looks like

[{'name': 'red', 'test':4},... {'name': 'reded', 'test':44}]`

I have a name (for example: reded) and I want to find the dictionary in the list above that has name in the dictionary set to reded. What is a concise way of doing so?

My attempts look something similar to

x = [dict_elem for dict_elem in list_above if dict_elem['name']==reded]

Then I do

final_val = x[0]

if the name gets matched. This can also be done with a for loop but it just seems like there is a simple one-liner for this. Am I missing something?

Eric
  • 95,302
  • 53
  • 242
  • 374
James Lam
  • 1,179
  • 1
  • 15
  • 21
  • Well, you can substitute your first line into your second... `[dict_elem for dict_elem in list_above if dict_elem['name']==reded][0]` – Eric May 26 '15 at 22:56

1 Answers1

2

You're pretty much there. If you use a generator- rather than list-comprehension, you can then pass it to next, which takes the first item.

try:
    x = next(dict_elem for dict_elem in list_above if dict_elem['name'] == reded)
except StopIteration:
    print "No match found"

Or

x = next((dict_elem for dict_elem in list_above if dict_elem['name'] == reded), None)
if not x:
    print "No match found"
Eric
  • 95,302
  • 53
  • 242
  • 374