user14504696
user14504696

Reputation: 23

Error when taking a subset of a dictionary in Python

I have a dictionary Retweets containing tweets information. The data structure of a tweet is like this:

[{'retweet_count': 338,
  'user': {'description': 'description1.',
   'followers_count': 582,
   'screen_name': 'screen_name1'}
 }
]

I want to take only the screen_name of the user and corresponding description into a new dict. Make this into a dict like this:

{'screen_name1': 'description1',
 'screen_name2': 'description2',
 'screen_name3': 'description3'
}

Here is my code:

user_list = []
for retweet in Retweets:
    user_list.append(retweet["user"]["screen_name"])
    final_dict = {key: retweet["user"]["description"] for key in user_list}

print(final_dict)

However, the descriptions of all users are the description of the last user. Like this:

{'screen_name1': 'description3',
 'screen_name2': 'description3',
 'screen_name3': 'description3'
}

Could anyone help me with this problem? Thank you!

Upvotes: 2

Views: 56

Answers (4)

Stevo
Stevo

Reputation: 298

You should put both the key and value in the dict comprehension

final_dict = {retweet["user"]["screen_name"]: retweet["user"]["description"] for retweet in Retweets}
    

Upvotes: 1

Masklinn
Masklinn

Reputation: 42632

However, the descriptions of all users are the description of the last user. Like this:

Well yes, consider what your code is doing:

for retweet in Retweets:
    final_dict = {key: retweet["user"]["description"] for key in user_list}

id the same as

for retweet in Retweets:
    final_dict = {}
    for key in user_list:
        final_dict[key] = retweet['user']['description']

So for each "retweet", you set the dict to mapping every entry in user_list to the RT's user's description.

Meaning you'll first create a dict mapping every screen name to the description of the first user, throw it away, re-create one mapping every screen name to the description of the second user, throw it away, ... until the last.

Since the screen names and descriptions are in the same place, you can just create the final dict correctly in one shot: instead of just extracting the screen_name, you can extract both screen name and description in the initial loop and create your dict immediately.

Upvotes: 0

Selcuk
Selcuk

Reputation: 59444

You are overwriting final_dict in your second for loop. That being said, you don't need that at all. You can simply use a dictionary comprehension:

final_dict = {d["user"]["screen_name"]: d["user"]["description"] 
              for d in Retweets}

Upvotes: 1

Abhinav Mathur
Abhinav Mathur

Reputation: 8196

You can do that in one loop only

tweets = {}
for retweet in Retweets:
    tweets[retweet["user"]["screen_name"]] = retweet["user"]["description"]
print(tweets)

Upvotes: 1

Related Questions