Search code examples
pythondictionaryfor-looptwitter

Replace a string inside a dictionary that's inside a list of dictionaries (Tweets from Twitter)


I have a list of tweets I collected from the Twitter API.

Each tweet in the list is in the form of a dictionary.

I want to change all of the strings 'en-gb' within this file to 'en'.

Here is a list of two of the tweets:

twitter_tweets =  
[{'created_at': 'Wed Oct 18 22:20:30 +0000 2017', 'id': 920776631102214144, 'user': {'id': 119116331, 'statuses_count': 32796, 'verified': False, 'lang': 'en-'}, 'retweet_count': 0, 'favorite_count': 0}
{'created_at': 'Wed Oct 17 12:20:36 +0000 2017', 'id': 920776631106514144, 'user': {'id': 119159331, 'statuses_count': 32796, 'verified': False, 'lang': 'en-gb'}, 'retweet_count': 1, 'favorite_count': 2}]

Note the location of the "en-gb" string:

While each tweet is a dictionary, the key 'user' has a secondary dictionary as its value. One of the keys inside that secondary dictionary is 'lang' (Language) and, its value is sometimes 'en-gb' ("British English").

I want to change all of the values 'en-gb' to 'en'.

I tried this, but to no avail:

for item in enumerate(twitter_tweets):
    for item == 'en-gb':
        item = 'en'

Solution

  • You can replace them by iterating through the list

    for d in twitter_cumulative_datascience_tweets:
        if d['user']['lang'] == 'en-gb':
            d['user']['lang'] = 'en'