Clear all

[Solved] Python Data Science Toolbox (Part 1)  



I can not pass the exercise for "Bringing it all together (1)", for the following 2 parts:

1. Complete the for loop by iterating over col, the 'lang' column in the DataFrame df.

2. Complete the bodies of the if-else statements in the for loop: if the key is in the dictionary langs_count, add 1 to the value corresponding to this key in the dictionary, else add the key to langs_count and set the corresponding value to 1. Use the loop variable entry in your code.


Please advise where can I find more information to pass this?

1 Answer

Try this:


import pandas as pd
# Import Twitter data as DataFrame: df
df = pd.read_csv('tweets.csv')
# Initialize an empty dictionary: langs_count
langs_count = {}
# Extract column from DataFrame: col
col = df['lang']
# Iterate over lang column in DataFrame
for entry in col:   
# If the language is in langs_count, add 1
if entry in langs_count.keys():
langs_count[entry] += 1
# Else add the language to langs_count, set the value to 1
langs_count[entry] = 1
# Print the populated dictionary
This post was modified 4 months ago by Yi Sheng

Thank you!!!


hi, are you able to explain the following line? as i dont recall coming across += before. thanks!

langs_count[entry] += 1


x += y
means x will increase itself by y then store it back into x.

langs_count[entry] += 1
is the same as
langs_count[entry] = langs_count[entry] + 1


Delete your account