Skip to content

Instantly share code, notes, and snippets.

@shostelet
Last active August 29, 2015 14:23
Show Gist options
  • Save shostelet/91edcc0b4550c98574c8 to your computer and use it in GitHub Desktop.
Save shostelet/91edcc0b4550c98574c8 to your computer and use it in GitHub Desktop.
Get one element (object, dict) within a list if attribute match something
mList = [
{
"name": "Alice",
"age": 19,
"slug_name": "alice"
},
{
"name": "Bob",
"age": 20,
"slug_name": "bob"
},
{
"name": "Charles",
"age": 21,
"slug_name": "charles"
},
{
"name": "Alice",
"age": 22,
"slug_name": "alice-1"
}
]
# get the dict within the list matching the searched name
next((user for (index, user) in enumerate(mList) if user['slug_name'] == searched_value), some_default_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment