Getting frequency of followers in subset of followers

Question:

I am creating a python twitter bot using Tweepy. In this snippet of code I am grabbing a list of recently followed accounts (50 per twitter user checked).

while count < int(numOfIDs):
    print(twitterUsernameArray[count] + " follows these accounts:")
    response = client.get_users_following(id=twitterIDArray[count], max_results=50, user_fields=['username'])
    for user in response.data:
        followerArray.append(user.username)
    count += 1

followerArray.sort()
print(followerArray)

I would like to be able to print out the common accounts. For instance say Person A recently followed accounts 1 and 2 and Person B recently followed accounts 2 and 3. I would like to be able to print out my list of recently followed accounts in the following way:

2 followed by 2 accounts
1 followed by 1 account
3 followed by 1 account

Thank you for any help!

Asked By: PackaLacken

||

Answers:

Since you are trying to get a frequency of followed accounts you should use a dictionary instead of using a list. Using a dictionary you can set the key with the username and then add the frequency as the key value to do something like this:

follower_dict = {}
while count < int(numOfIDs):
    print(twitterUsernameArray[count] + " follows these accounts:")
    response = client.get_users_following(id=twitterIDArray[count], max_results=50, user_fields=['username'])
    for user in response.data:
        if user.username in follwer_dict:
            follower_dict[user.username] += 1 # incrementing the count if the username is in the dictionary
        else:
            follower_dict[user.username] = 1 # adding an initial value to the dictionary as the username is not in the dictionary
    count += 1

print(follower_dict) # will print out the frequency dict like: {A: 1, B: 2, C: 1}

Hope this is what you are looking for.

Answered By: Andrew Ryan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.