[英]How to count the unique values of a column and append each value to a dictionary?
The tutorial suggests this solution本教程建议使用此解决方案
opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
content_ratings = {}
for row in apps_data[1:]:
c_rating = row[10] #the content rating that says which app is suitable for which age
if c_rating in content_ratings:
content_ratings[c_rating] += 1
else:
content_ratings[c_rating] = 1
print(content_ratings)
The output is output 是
{'17+': 622, '4+': 4433, '9+': 987, '12+': 1155}
I just want to understand the code logic.我只是想了解代码逻辑。 The line says
if c_rating in content_ratings:
is supposed to return False
as it doesn't meet the condition since the content_rating
itself is empty so c_rating
is not in the dictionary.该行说
if c_rating in content_ratings:
应该返回False
因为它不满足条件,因为content_rating
本身是空的,所以c_rating
不在字典中。 How does this logic find the content rating and append it to the dictionary?这个逻辑如何在字典中找到内容分级和 append?
Both lines in if-else statement looks same, but there is slight difference, +
sign: if-else 语句中的两行看起来相同,但略有不同,
+
号:
if c_rating in content_ratings:
content_ratings[c_rating] += 1
else:
content_ratings[c_rating] = 1
content_ratings[c_rating] = 1
this is how an element is added into dictionary in python. content_ratings[c_rating] = 1
这是在 python 中将元素添加到字典中的方式。 Also you can update existed element dictionary in same way;您也可以以相同的方式更新现有的元素字典; here
content_ratings[c_rating] += 1
you get the existing element and increase its value.在这里
content_ratings[c_rating] += 1
你得到了现有的元素并增加了它的价值。
So, you are right, when if c_rating in content_ratings:
returns false
, it adds elements, otherwise, it updates its value (increasing count).所以,你是对的,
if c_rating in content_ratings:
返回false
,它会添加元素,否则,它会更新它的值(增加计数)。
You can see basic operation on dictionary in docs.您可以在文档中查看字典的基本操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.