Last active
August 29, 2015 14:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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