Python Forum
Creating a loop with dynamic variables instead of hardcoded values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a loop with dynamic variables instead of hardcoded values
#1
The first step is creating a dataframe of usernames and their corresponding User IDs. You also need to login to an Instagram account for authentication purposes.

  from instagram_private_api import Client, ClientCompatPatch
    from operator import itemgetter
    import pandas as pd
    import json
    import requests

    user_name = ''
    password = ''
    api = Client(user_name, password)

    influencers = [['dcfoodcravings', '5577994064'], ['dcfoodlovers', '1902259438'], ['excellence.beauty.lounge', '2213626850'], ['foodzie', '1486757'], ['fiolamaredc', '1109579078']]

    influencers_df = pd.DataFrame(influencers, columns=['username', 'userId'])
Once that's complete, we then move on to getting a list of their followers. This is where the issue is. You can see for the variables following_username, following_userid, and get_followers I am using **hard coded values.** But what I'm trying to do is run all the userId's (along with their corresponding username's in the influencers_df dataframe in a loop with dynamic variables.

So the end product would be list of all the followers from those username/userid combinations in the influencers_df dataframe.

 def followers_users(userid_instagram):
        followers = []
        combined = []
        results = api.user_followers(userid_instagram, rank_token=api.generate_uuid())
        followers.extend(results.get('users', []))
        next_max_id = results.get('next_max_id')
        while next_max_id:
            results = api.user_followers(userid_instagram, rank_token=api.generate_uuid(), max_id=next_max_id)
            followers.extend(results.get('users', []))
            next_max_id = results.get('next_max_id')
        userid = [followers[i]['pk'] for i in range(0,len(followers))]
        full_names = [followers[i]['full_name'] for i in range(0,len(followers))]
        usernames = [followers[i]['username'] for i in range(0,len(followers))]
        profile_pic_url = [followers[i]['profile_pic_url'] for i in range(0,len(followers))]
        followers_text = ['follower' for i in range(0,len(followers))]
        following_username = ['dcfoodcravings' for i in range(0,len(followers))]
        following_userid = ['5577994064' for i in range(0,len(followers))]
        combined.extend([list(i) for i in zip(userid, full_names,
                                                usernames, profile_pic_url, followers_text,
                                                following_username, following_userid)])
        combined = sorted(combined, key=itemgetter(2), reverse=False)
        return(combined)
    get_followers = followers_users('5577994064')
    followers = pd.DataFrame(get_followers, columns = ['userID' , 'Full Name', 'username', 'Profile Picture', 'Type', 'following_username', 'following_userid'])
    followers
Reply
#2
If you don't know how to iterate over values in a dataframe series you should write a small program that focuses on doing that. Toe in, not jump in. Jump in is ok if you have a strong programming background with another language and all you are learning is syntax and libraries, but from your code example above I don't think you have that.
Reply
#3
(Jul-27-2022, 06:45 PM)deanhystad Wrote: If you don't know how to iterate over values in a dataframe series you should write a small program that focuses on doing that. Toe in, not jump in. Jump in is ok if you have a strong programming background with another language and all you are learning is syntax and libraries, but from your code example above I don't think you have that.

Okay, so how would you write the code I posted? I learn best by seeing what a final product would look like and then working backwards.
Reply
#4
It is a style of Python coding that I've not come across before and must be a real mear to debug.

As an example, your code line...

followers_text = ['follower' for i in range(0,len(followers))]
... I would code as...

for i in range(len(followers)):
    followers_text.append('follower')
... that said, I don't see that it's doing anything other than add the string 'follower' to the list object followers_text[] for as many times as there are item in the list object followers[].

Where did you learn this style?
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through values and compare edroche3rd 6 684 Oct-18-2023, 04:04 PM
Last Post: edroche3rd
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,097 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Transposing a dataframe without creating NaN values doug2019 2 979 Mar-18-2023, 03:14 PM
Last Post: jefsummers
  Need help with creating dynamic columns with for loops for stock prices PaDat 2 896 Feb-22-2023, 04:34 AM
Last Post: PaDat
  How do loop over curl and 'put' different values in API call? onenessboy 0 1,219 Jun-05-2022, 05:24 AM
Last Post: onenessboy
  Create array of values from 2 variables paulo79 1 1,082 Apr-19-2022, 08:28 PM
Last Post: deanhystad
  Creating a numpy array from specific values of a spreadsheet column JulianZ 0 1,114 Apr-19-2022, 07:36 AM
Last Post: JulianZ
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,477 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  Loop through values in dictrionary and find the same as in previous row Paqqno 5 1,901 Mar-27-2022, 07:58 PM
Last Post: deanhystad
  How to add for loop values in variable paulo79 1 1,441 Mar-09-2022, 07:20 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020