Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing what Twitter followers are followed by friends in Python/Django

I'm building a quick part of my app that looks at a user's followers, and highlights which ones are followed by people the user follows (friends).

I'm wondering two things:

  1. Is there a more efficient way to do this? Seems like this will run up Twitter's API limits because I need to check friends of every one the user's friends.

  2. This is creating a list of dicts containing the friend id and the followers they follow. Instead, the dict would be better as the follower id and then the friends who follow them. Tips?

Code:

# Get followers and friends
followers = api.GetFollowerIDs()['ids']
friends = api.GetFriendIDs()['ids']

# Create list of followers user is not following
followers_not_friends = set(followers).difference(friends)

# Create list of which of user's followers are followed by which friends
followers_that_friends_follow = []
for f in friends:
    ff = api.GetFriendIDs(f)['ids']
    users = followers_not_friends.intersection(ff)
    followers_that_friends_follow.append({'friend': f, 'users': users })
like image 216
Brenden Avatar asked Nov 15 '22 02:11

Brenden


1 Answers

For the second part of your question:

import collections

followers_that_friends_follow = collections.defaultdict(list)
for f in friends:
    ff = api.GetFriendsIDs(f)['ids']
    users = followers_not_friends.intersection(ff)
    for user in users:
        followers_that_friends_follow[user].append(f)

that will result in a dictionary with:

keys = ids followers that follow the user, that the user doesn't follow, and are followed by user's friends.

values = list of id's of friends that follow the follower, that the user doesn't follow

for example if the user's follower has an id of 23 and two of the user's friends (user 16 and user 28) follow user 23, using key 23 should give the following result

>>> followers_that_friends_follow[23]
[16,28]
like image 145
dting Avatar answered Dec 27 '22 23:12

dting