Skip to content

Instantly share code, notes, and snippets.

@stupidbodo
Last active August 29, 2015 14:03
Show Gist options
  • Save stupidbodo/614b6e77d54fb5870f3a to your computer and use it in GitHub Desktop.
Save stupidbodo/614b6e77d54fb5870f3a to your computer and use it in GitHub Desktop.
Python Combine "for" and "if" statement - Useful for loopping through JSON and find data using keys
users = [{
"user_id": 1,
"hobby": "Play Football"
}, {
"user_id": 1,
"hobby": "Play Basketball"
}]
# Given data above, if you want loop through the JSON and check if a specific user exist,
# you can do it with the code below.
user_exist = False
for user in users:
if user['user_id'] == 1:
user_exist = True
# do other stuffs
if not user_exist:
# user don't exist
# Another way to do this is to use the generator expression.
gen = (True for user in users if user['user_id'] == 1)
if True not in gen:
# user don't exist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment