rohit nair rohit nair - 2 years ago 70
Python Question

Finding the exact match of many usernames stored in a variable while looping

I have a code which sends usernames from an excel sheet as an input which is stored in a variable xy to an instagram API which in return gives the results. I load the URL to a JSON to get it in a json schema.

For example when my variable xy contains "shawn_123" the result from the API is:

"meta": {
"code": 200
"data": [
"username": "shawn_123",
"profile_picture": " 19/s150x150/11417456_1610194859266611_592197892_a.jpg",
"id": "641567093",
"full_name": "shawn ritz"
"username": "shawn_12345",
"profile_picture": "",
"id": "2074312361",
"full_name": "shawney"

And my code is

for r in range(1,10):
for item in beta['data']:

As it is retrieving two outputs from a same username.

Note: I want a regular expression which searches the exact username from the json and save the user_id of only that record.

Answer Source

You can check if the username matches before printing the id:

for item in beta['data']:
    if item['username'] == xy: # here check the username from your input

Or, using next operator:

user_id = next((item['id'] for item in beta['data'] if item['username'] == xy), None)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download